<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);
$admin = $_SESSION["admin_" . $dbname];
$success = false;

$itemname = $_REQUEST["itemname"];
$file = $_REQUEST["file"];


if ($file == 'sale_ti.php' || $file == 'crednote.php' || $file == 'invoexp.php') {
    $rate = "rate";
} else {
    $rate = "cost";
}

if (isset($itemname) != "") {

    $party = $_REQUEST["party"];

    $query = "SELECT `name`, `barcode`, `prodcode`, `gram`, `unit` , `hsncode`, `gstperc`, `mrp`, `rate`
               FROM `product` WHERE name='$itemname'";
    $result = mysqli_query($conn, $query)or die(mysqli_error($conn));

    $r = mysqli_fetch_assoc($result);
    $n = mysqli_num_rows($result);

//    $mrate = mysqli_query($conn, "SELECT `rate` FROM `product`  WHERE barcode='$barcode'") or die(mysqli_error($conn));
//    $frate = mysqli_fetch_array($mrate);

    $ra = $r[rate];

    $mdisc = mysqli_query($conn, "SELECT `disc1`, `disc2`, `disc3`, `disc4` FROM `accmast` WHERE accode='$party'") or die(mysqli_error($conn));
    $fdisc = mysqli_fetch_array($mdisc);
    
    $gstperc = mysqli_query($conn, "SELECT `per`, `code` FROM `gsttype` WHERE code='$r[gstperc]'") or die(mysqli_error($conn));
    $fgstperc = mysqli_fetch_array($gstperc);

    $d1 = $fdisc[disc1];
    $d2 = $fdisc[disc2];
    $d3 = $fdisc[disc3];
    $d4 = $fdisc[disc4];

    if (!empty($d1)) {
        $discval = ($ra * $d1) / 100;
        $ra = $ra - $discval;
    }

    if (!empty($d2)) {
        $discval = ($ra * $d2) / 100;
        $ra = $ra - $discval;
    }
    if (!empty($d3)) {
        $discval = ($ra * $d3) / 100;
        $ra = $ra - $discval;
    }
    if (!empty($d4)) {
        $discval = ($ra * $d4) / 100;
        $ra = $ra - $discval;
    }
    $ra = round($ra,2);
    if ($n > 0) {
        $success = true;
    }


    $rows = array('success' => $success,
        'name' => $r[name],
        'barcode' => $r[barcode],
        'itemcode' => $r[prodcode],
        'gram' => $r[gram],
        'unit' => $r[unit],
        'rate' => $r[rate],
        'hsncode' => $r[hsncode],
        'mrp' => $r[mrp],
        'gstperc' => $fgstperc[per]
    );
    header("Content-type: application\json");
    echo json_encode($rows);
}