<?php require_once('../auth/auth.php');
require_once('../auth/acid_balance.php'); ?>
<?php
if (isset($_POST['eretsal_invoice'])) {
    $invoice    = $_POST['eretsal_invoice'];
    $tdate      = $_POST['etdate'] . ' ' . $time;
    $c_acid     = $_POST['ec_acid'];
    $f_acid     = $_POST['ef_acid'];
    $d_acid     = $_POST['ed_acid'];
    $discount   = $_POST['esldiscount'];
    $delivary_c = $_POST['edelivary_c'];
    $m_acid     = $_POST['em_acid'];
    $payment    = $_POST['eslpayment'];
    $details    = $_POST['edetails'];
    $wh_id      = $_POST['ewh_id'];
    $d_man      = $_POST['ed_man'];
    $m_invoice  = $_POST['em_invoice'];
    $net_amount = $_POST['esl_totalc'];

    $sltyperow = mysqli_query($conn, "SELECT order_type,ex_invoice FROM order_list_edit WHERE coid='$coid' AND bid='$bid' AND brid='$brid' 
     AND invoice='$invoice' ");
    $srow = mysqli_fetch_assoc($sltyperow);
    $sltype = $srow['order_type'];
    $ex_invoice = $srow['ex_invoice'];
    if ($sltype == 'ESRTN') {
        $rec_type = 'SR_P';
    }


    if (isset($_POST['ec_gsm'])) {
        $c_gsm     = $_POST['ec_gsm'];
        $c_name    = $_POST['ec_name'];
        $c_address = $_POST['ec_address'];
        $payment   = (($net_amount + $delivary_c) - $discount);

        $chcus = mysqli_query($conn, "SELECT c_id FROM c_customer WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND c_gsm='$c_gsm' ");

        if (mysqli_num_rows($chcus) < 1) {
            mysqli_query($conn, "INSERT INTO `c_customer`(`coid`, `bid`, `brid`, `c_name`, `c_gsm`, `c_address`) VALUES ('$coid','$bid','$brid','$c_name','$c_gsm','$c_address')") or die(mysqli_error($conn));
        }

        $c_cus = mysqli_fetch_assoc(mysqli_query($conn, "SELECT c_id FROM c_customer WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND c_gsm='$c_gsm' "))['c_id'];
    }

    $c_id = @$c_cus ? $c_cus : $uid;

    if ($net_amount > 0.01) {

        // Delete Part Start ///

        $puinv = mysqli_query($conn, "SELECT dr_acid,cr_acid FROM transaction WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));
        $stacid = [];
        while ($stc = mysqli_fetch_assoc($puinv)) {
            array_push($stacid, $stc['dr_acid'], $stc['cr_acid']);
        }

        // mysqli_query($conn, "DELETE FROM order_list WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));
        // mysqli_query($conn, "DELETE FROM transaction WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));

        // Delete Part END ///

        if (date("Y-m-d", strtotime($datetime)) == $_POST['etdate']) {

            $time       = date("H:i:s", strtotime($datetime));
            $tdate      = $_POST['etdate'] . ' ' . $time;
        }

        // New Insert Part Start ///

        mysqli_query($conn, "INSERT INTO `order_list`(`coid`, `bid`, `brid`, `acid`, `invoice`,`ex_invoice`, `order_type`, `wh_id`, `pro_id`, `item_code`, `pro_type`, `plus`, `qty`, `pro_unit`, `unit_val`, `out_qty`, `run_qty`, `pu_price`, `avg_price`, `sale_price`,`change_slprice`, `discount`, `dis_amount`, `amount`, `net_amount`, `t_amount`, `tax`, `profit`, `details`, `d_man`, `userid`, `datetime`, `active`) 
        SELECT `coid`, `bid`, `brid`, '$c_id', `invoice`,`ex_invoice`, `order_type`, '$wh_id', `pro_id`, `item_code`, `pro_type`, `plus`, (qty*unit_val), `pro_unit`, `unit_val`, `out_qty`, `run_qty`, `pu_price`, `avg_price`, `sale_price`,`change_slprice`, `discount`, `dis_amount`, `amount`, `net_amount`, `t_amount`, `tax`, `profit`, `details`, '$d_man', `userid`, '$tdate', 1 FROM `order_list_edit` WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND qty > 0 AND  invoice='$invoice'") or die(mysqli_error($conn));


        $c_gcatid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$c_acid' "))['gcatid'];

        $sl_row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='sale' "));
        $sl_acid   = $sl_row['acid'];
        $sl_gcatid = $sl_row['gcatid'];

        $inv_row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='stock' "));
        $inv_acid   = $inv_row['acid'];
        $inv_gcatid = $inv_row['gcatid'];

        $cogs_row = mysqli_fetch_assoc(mysqli_query($conn, "SELECT acid,gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND ac_type='cogs' "));
        $cogs_acid   = $cogs_row['acid'];
        $cogs_gcatid = $cogs_row['gcatid'];

        $avg_total = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(avg_price*qty) avg_cost FROM order_list WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'"))['avg_cost'];

        mysqli_query($conn, "INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,ex_invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$sl_acid', '$c_acid', '$c_id', '$sl_gcatid', '$c_gcatid', '$invoice','$ex_invoice','$m_invoice', 'ESRTN','$details','esalereturn','$net_amount','$tdate','$time','$uid','$uid','1'),
          ('$coid','$bid','$brid','$inv_acid', '$cogs_acid', '$uid', '$inv_gcatid', '$cogs_gcatid', '$invoice','$ex_invoice','$m_invoice', 'COGS','$details','esalereturn','$avg_total','$tdate','$time','$uid','$uid','1')") or die(mysqli_error($conn));

        mysqli_query($conn, "DELETE FROM order_list_edit WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND invoice='$invoice'") or die(mysqli_error($conn));

        if ($f_acid > 0 && $delivary_c > 0) {

            $f_gcatid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$f_acid' LIMIT 1"))['gcatid'];

            mysqli_query($conn, "INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,ex_invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$f_acid', '$c_acid', '$uid', '$f_gcatid', '$c_gcatid', '$invoice','$ex_invoice','$m_invoice', 'P','Delevery Charge','esale_delivary','$delivary_c','$tdate','$time','$uid','$uid','1')") or die(mysqli_error($conn));

            $tmp_f = balance($f_acid)['ac_balance'];
            $f_acid_balance = (@$tmp_f) ? $tmp_f : 0;
            mysqli_query($conn, "UPDATE accounts SET balance='$f_acid_balance' WHERE coid='$coid' AND acid ='$f_acid' LIMIT 1") or die(mysqli_error($conn));
        }

        if ($d_acid > 0 && $discount > 0) {

            $d_gcatid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$d_acid' LIMIT 1"))['gcatid'];

            mysqli_query($conn, "INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,ex_invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$c_acid', '$d_acid', '$uid', '$c_gcatid', '$d_gcatid', '$invoice','$ex_invoice','$m_invoice', 'SR_D','Sales Return Discount','esalereturn_discount','$discount','$tdate','$time','$uid','$uid','1')") or die(mysqli_error($conn));

            $tmp_d = balance($d_acid)['ac_balance'];
            $d_acid_balance = (@$tmp_d) ? $tmp_d : 0;
            mysqli_query($conn, "UPDATE accounts SET balance='$d_acid_balance' WHERE coid='$coid' AND acid ='$d_acid' LIMIT 1") or die(mysqli_error($conn));
        }

        if ($m_acid > 0 && $payment > 0) {

            $m_gcatid = mysqli_fetch_assoc(mysqli_query($conn, "SELECT gcatid FROM accounts WHERE coid='$coid' AND bid='$bid' AND brid='$brid' AND acid='$m_acid' LIMIT 1"))['gcatid'];

            mysqli_query($conn, "INSERT INTO transaction(coid,bid,brid,dr_acid,cr_acid,e_acid,dr_gcatid,cr_gcatid,invoice,ex_invoice,m_invoice,ttype,details,note,amount,date,ptime,userid,em_id,active) 
          VALUES ('$coid','$bid','$brid','$c_acid', '$m_acid', '$uid', '$c_gcatid', '$m_gcatid', '$invoice','$ex_invoice', '$m_invoice', '$rec_type','Sales Retrun Payment','return_payment','$payment','$tdate','$time','$uid','$uid','1')") or die(mysqli_error($conn));

            $tmp_m = balance($m_acid)['ac_balance'];
            $m_acid_balance = (@$tmp_m) ? $tmp_m : 0;
            mysqli_query($conn, "UPDATE accounts SET balance='$m_acid_balance' WHERE coid='$coid' AND acid ='$m_acid' LIMIT 1") or die(mysqli_error($conn));
        }

        $tmp_inv  = balance($inv_acid)['ac_balance'];
        $tmp_c    = balance($c_acid)['ac_balance'];
        $tmp_sl   = balance($sl_acid)['ac_balance'];
        $tmp_cogs = balance($cogs_acid)['ac_balance'];

        $inv_acid_balance  = (@$tmp_inv) ? $tmp_inv : 0;
        $c_acid_balance    = (@$tmp_c) ? $tmp_c : 0;
        $sl_acid_balance   = (@$tmp_sl) ? $tmp_sl : 0;
        $cogs_acid_balance = (@$tmp_cogs) ? $tmp_cogs : 0;

        mysqli_query($conn, "UPDATE accounts SET balance='$inv_acid_balance' WHERE coid='$coid' AND acid ='$inv_acid' LIMIT 1") or die(mysqli_error($conn));
        mysqli_query($conn, "UPDATE accounts SET balance='$c_acid_balance' WHERE coid='$coid' AND acid ='$c_acid' LIMIT 1") or die(mysqli_error($conn));
        mysqli_query($conn, "UPDATE accounts SET balance='$sl_acid_balance' WHERE coid='$coid' AND acid ='$sl_acid' LIMIT 1") or die(mysqli_error($conn));
        mysqli_query($conn, "UPDATE accounts SET balance='$cogs_acid_balance' WHERE coid='$coid' AND acid ='$cogs_acid' LIMIT 1") or die(mysqli_error($conn));


        // New Insert Part END ///


        // Change Accounts Balance Update Start ///

        $chacid = array_diff($stacid, [$c_acid, $f_acid, $d_acid, $m_acid, $inv_acid, $sl_acid, $cogs_acid]);
        if (!empty($chacid)) {
            foreach (array_unique($chacid) as $acid) {

                $tmp_bal = balance($acid)['ac_balance'];
                $acid_balance = (@$tmp_bal) ? $tmp_bal : 0;
                mysqli_query($conn, "UPDATE accounts SET balance='$acid_balance' WHERE coid='$coid' AND acid ='$acid' LIMIT 1") or die(mysqli_error($conn));
            }
        }
        // Change Accounts Balance Update Start ///  


        if (isset($_POST['email'])) {
            // Email Part Here
        }

        if (isset($_POST['sms'])) {
            // SMS Part Here
        }
    }
}
?>