<?php 
include("../config.php");

if(!empty($_POST)){
    if($_POST["id"] != '')
    {
       $lr_no = mysqli_real_escape_string($conn, $_POST['lr_no']);
    }
    else
    {
        $lr_no = mysqli_real_escape_string($conn, strtoupper($prifix) . '/' . str_pad(($_POST['lr_no']), 5, '0', STR_PAD_LEFT));

        $checkpoint = mysqli_query($conn,"SELECT id FROM  lr_mst WHERE lr_no = '".$lr_no."' AND branch_id = '".$_SESSION['branch_id']."' AND company_id = '".$_SESSION['company_id']."'");

        if(mysqli_num_rows($checkpoint) > 0)
        {
            $lr_no = strtoupper($prifix) . '/' . str_pad(lrCode($conn), 5, '0', STR_PAD_LEFT);
        }
    } 

    $lr_type             = mysqli_real_escape_string($conn, $_POST['lr_type']);
    $l_date              = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['l_date'])));
    $party_invoice       = mysqli_real_escape_string($conn, $_POST['party_invoice']);
    $party_amount        = mysqli_real_escape_string($conn, $_POST['party_amount']);
    $truck_no            = mysqli_real_escape_string($conn, $_POST['truck_no']);
    $from_place          = mysqli_real_escape_string($conn, $_POST['from_place']);
    $to_place            = mysqli_real_escape_string($conn, $_POST['to_place']);
    $consignor_name      = mysqli_real_escape_string($conn, $_POST['consignor_name']);
    $consignee_name      = mysqli_real_escape_string($conn, $_POST['consignee_name']);
    if(!empty($_POST['billing_to'])){
        $billing_to      = mysqli_real_escape_string($conn, $_POST['billing_to']);
    }else{
        $billing_to = '';
    }

    $agent               = mysqli_real_escape_string($conn, $_POST['agent']);
    $nature_of_goods     = mysqli_real_escape_string($conn, $_POST['nature_of_goods']);
    $weight              = mysqli_real_escape_string($conn, $_POST['weight']);
    $actual_weight       = mysqli_real_escape_string($conn, $_POST['actual_weight']);
    $height              = mysqli_real_escape_string($conn, $_POST['height']);
    $pcs                 = mysqli_real_escape_string($conn, $_POST['pcs']);
    $rate                = mysqli_real_escape_string($conn, $_POST['rate']);
    $challan_no          = mysqli_real_escape_string($conn, $_POST['challan_no']);
    $gst_paid_by         = mysqli_real_escape_string($conn, $_POST['gst_paid_by']);
    $insured_by         = mysqli_real_escape_string($conn, $_POST['insured_by']);
    $billing_party       = mysqli_real_escape_string($conn, $_POST['billing_party']);
    $remark              = mysqli_real_escape_string($conn, $_POST['remark']);
    $rate_on             = mysqli_real_escape_string($conn, $_POST['rate_on']);
    $lr_mode             = mysqli_real_escape_string($conn, $_POST['lr_mode']);
    $delivery             = mysqli_real_escape_string($conn, $_POST['delivery']);
    $freight             = mysqli_real_escape_string($conn, $_POST['freight']);
    $truck_driver_no     = mysqli_real_escape_string($conn, $_POST['truck_driver_no']);
    $eway_bill_no        = mysqli_real_escape_string($conn, $_POST['eway_bill_no']);
    $notes    = mysqli_real_escape_string($conn, $_POST['notes']);
    $packing             = mysqli_real_escape_string($conn, $_POST['packing']);
    $insurance_date      = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['insurance_date'])));
    $eway_date           = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['eway_date'])));
    $eway_ex_date        = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['eway_ex_date'])));
    $invoice_date        = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['invoice_date'])));
    $po_no               = mysqli_real_escape_string($conn, $_POST['po_no']);
    $po_date             = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['po_date'])));
    $lorry_type          = mysqli_real_escape_string($conn, $_POST['lorry_type']);
    $total_actual_weight  = mysqli_real_escape_string($conn, $_POST['total_actual_weight']);
    $total_charged_weight  = mysqli_real_escape_string($conn, $_POST['total_charged_weight']);
    // $delivery_address  = mysqli_real_escape_string($conn, $_POST['delivery_address']);
    $to_be_billed_at  = mysqli_real_escape_string($conn, $_POST['to_be_billed_at']);
    $st_charges  = mysqli_real_escape_string($conn, $_POST['st_charges']);
    $insurance_status  = mysqli_real_escape_string($conn, $_POST['insurance_status']);
    $policy_no  = mysqli_real_escape_string($conn, $_POST['policy_no']);
    $mode  = mysqli_real_escape_string($conn, $_POST['mode']);
     $tracking_status     = 'E';
    $company_id          = $_SESSION['company_id'];
    $branch_id           = $_SESSION['branch_id'];
    $created_datetime    = risFormatDate($_POST['l_date'], 'Y-m-d H:i:s');
    $created_id          = $_SESSION['user_detail']['id'];
    $updated_datetime    = date('Y-m-d H:i:s');
    $updated_id          = $_SESSION['user_detail']['id'];
    $expense              = $_POST['expense'];

    $consignor_vendor_address = mysqli_real_escape_string($conn, $_POST['consignor_address']);
    $consignor_vendor_city    = mysqli_real_escape_string($conn, $_POST['consignor_city']);
    $consignor_vendor_contact = mysqli_real_escape_string($conn, $_POST['consignor_contact']);
    $consignor_vendor_pan     = mysqli_real_escape_string($conn, $_POST['consignor_pan']);
    $consignor_vendor_gstin   = mysqli_real_escape_string($conn, $_POST['consignor_gst']);

    $consignee_vendor_name    = mysqli_real_escape_string($conn, $_POST['consignee_name']);
    $consignee_vendor_address = mysqli_real_escape_string($conn, $_POST['consignee_address']);
    $consignee_vendor_city    = mysqli_real_escape_string($conn, $_POST['consignee_city']);
    $consignee_vendor_contact = mysqli_real_escape_string($conn, $_POST['consignee_contact']);
    $consignee_vendor_pan     = mysqli_real_escape_string($conn, $_POST['consignee_pan']);
    $consignee_vendor_gstin   = mysqli_real_escape_string($conn, $_POST['consignee_gst']);

    $description = $_POST['product'][0]['description'];
    $pcs         = $_POST['product'][0]['pcs'];

    if($_POST["id"] != ''){
        $type               = 'lr_update';
        $user_id            = $_SESSION['user_detail']['id'];
        $data               = serialize($_POST);

    // update
         $fetch_id = "SELECT * FROM `lr_mst` WHERE lr_no ='".$lr_no."'";
        $fetch_id_res = mysqli_query($conn,$fetch_id);
        $fetch_id_row = mysqli_fetch_assoc($fetch_id_res);

        $insert = "UPDATE lr_mst SET lr_type='$lr_type',lr_no='$lr_no',l_date='$l_date',
                  party_invoice='$party_invoice',party_amount='$party_amount',truck_no='$truck_no',
                  from_place='$from_place',to_place='$to_place',consignor_name='$consignor_name',
                  consignee_name='$consignee_name',billing_to='$billing_to',agent='$agent',
                  nature_of_goods='$description',weight='$weight',actual_weight='$actual_weight',
                  height='$height',pcs='$pcs',challan_no='$challan_no',gst_paid_by='$gst_paid_by',insured_by='$insured_by',
                  billing_party='$billing_party',remark='$remark',rate_on='$rate_on',
                  freight='$freight',insurance_date='$insurance_date',
                  truck_driver_no='$truck_driver_no',eway_bill_no='$eway_bill_no',
                  packing='$packing',charged_weight='$charged_weight',eway_date='$eway_date',
                  eway_ex_date='$eway_ex_date',invoice_date='$invoice_date',po_no='$po_no',
                  po_date='$po_date',notes='$notes',lorry_type='$lorry_type',
                  updated_id='$updated_id',updated_datetime='$updated_datetime'
                  ,consignee_address='$consignee_vendor_address',consignee_city = '$consignee_vendor_city
                  ', consignee_contact = '$consignee_vendor_contact',consignee_pan='$consignee_vendor_pan
                  ',consignee_gst='$consignee_vendor_gstin',total_actual_weight='$total_actual_weight',total_charged_weight='$total_charged_weight',to_be_billed_at='$to_be_billed_at',lr_mode='$lr_mode',delivery='$delivery',st_charges='$st_charges',insurance_status='$insurance_status',policy_no='$policy_no',mode='$mode'

                  WHERE lr_no='".$_POST['id']."' AND branch_id = '".$_SESSION['branch_id']."' AND 
                  company_id = '".$_SESSION['company_id']."'";
            $result = mysqli_query($conn,$insert);

            $delete_query = "DELETE FROM `lr_grid` WHERE `master_id` = '".$fetch_id_row['id']."'";
            $delete_query_result = mysqli_query($conn, $delete_query);

        foreach ($_POST['product'] as $product)
        {

            $master_id           = $fetch_id_row['id'];
            $description         = $product['description'];
            $pcs                 = $product['pcs'];
            $weight              = $product['weight'];
            $charged_weight      = $product['charged_weight'];
            $hsn_code            = $product['hsn_code'];
            $freight_rate        = $product['freight_rate'];
            if($description !=''){
            $insert_query = "INSERT INTO lr_grid (description, master_id, pcs, weight,charged_weight,hsn_code,freight_rate) 
            VALUES ('$description','$master_id','$pcs',
            '$weight','$charged_weight','$hsn_code','$freight_rate')";
            $insert_result = mysqli_query($conn, $insert_query);
            }
        }

        // activity
        $activiti = "INSERT INTO `activities`(`type`, `user_id`, `data`, `created_id`,
                                              `created_datetime`, `updated_id`, `updated_datetime`) 
                                              VALUES ('".$type."','".$user_id."','".$data."',
                                              '".$created_id."','".$created_datetime."',
                                              '".$updated_id."','".$updated_datetime."')";
        $acttivity_res = mysqli_query($conn,$activiti);
        }else{
           //insert begins from here
 
            $Vendor_Code     = vendorCode($conn);
            $act_code      = accountCode($conn);
            $check_truck_no = "SELECT * FROM `truck_mst` WHERE `truck_no` = '$truck_no'";
            $truck_no_result = mysqli_query($conn, $check_truck_no);
           if (mysqli_num_rows($truck_no_result) <= 0)
            {
                 $truck_code = turckCode($conn);
                $insert_truck_query   = mysqli_query($conn,"INSERT INTO `truck_mst` (`truck_no`,`truck_code`) VALUES ('$truck_no','$truck_code')");
            }
            // check consignor
            $check_consignor  = "SELECT * FROM `vendor_master` WHERE name = '".$consignor_name."'";
            $check_res        =  mysqli_query($conn, $check_consignor);
            if (mysqli_num_rows($check_res) <= 0){
                $consignor_query = mysqli_query($conn, "INSERT INTO `vendor_master`(`code`,`type`,`name`,`p_name`,`address`,`p_address`,`city`,`contact`,`pan`,`gstin`,`company_id`,`branch_id`,`created_id`,`created_datetime`,`updated_id`,`updated_datetime`)VALUES ('$Vendor_Code','V','$consignor_name','$consignor_name','$consignor_vendor_address','$consignor_vendor_address','$consignor_vendor_city','$consignor_vendor_contact','$consignor_vendor_pan','$consignor_vendor_gstin','$company_id','$created_id','$branch_id','$created_datetime','$updated_id','$updated_datetime')");
            }
            // check consignee
            $check_consignee  = "SELECT * FROM `vendor_master` WHERE name = '".$consignee_name."'";
            $consignee_res        =  mysqli_query($conn, $check_consignee);
            if (mysqli_num_rows($consignee_res) <= 0){
                $consignee_query = mysqli_query($conn, "INSERT INTO `vendor_master`(`code`,`type`,`name`,`p_name`,`address`,`p_address`,`city`,`contact`,`pan`,`gstin`,`company_id`,`branch_id`,`created_id`,`created_datetime`,`updated_id`,`updated_datetime`) VALUES ('$Vendor_Code','V',
                                  '$consignee_name','$consignee_name','$consignee_vendor_address',
                                  '$consignee_vendor_address','$consignee_vendor_city',
                                  '$consignee_vendor_contact','$consignee_vendor_pan',
                                  '$consignee_vendor_gstin','$company_id','$created_id','$branch_id',
                                  '$created_datetime','$updated_id','$updated_datetime')");
             }
            $check_agent  = "SELECT * FROM `vendor_master` WHERE name = '".$agent."'";
            $agent_res        =  mysqli_query($conn, $check_agent);
            if (mysqli_num_rows($agent_res) <= 0){
                $agent_entry_query = mysqli_query($conn, "INSERT INTO `vendor_master`(`code`,`type`,`name`,`p_name`,`company_id`,`branch_id`,`created_id`,`created_datetime`,`updated_id`,`updated_datetime`) VALUES ('$Vendor_Code', 'A', '$agent', '$agent', '$company_id', '$created_id', '$branch_id', '$created_datetime', '$updated_id', '$updated_datetime')");
             }
             // check account master

            $chk_agent_ac = "SELECT * FROM  `act_master` WHERE `ac_name` = '".$agent."'";
            $chk_agent_ac_query = mysqli_query($conn, $chk_agent_ac);
            if (mysqli_num_rows($chk_agent_ac_query) <= 0){
             $act_code      = accountCode($conn);
             $act_mst = "INSERT INTO `act_master`(`act_code`, `ac_name`, `dr_open_bal`, `cr_open_bal`, `account_group`, `party_code`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`)  VALUES ('".$act_code."','".$_POST['agent']."','0.00','0.00','SUNDRY CREDITORS','NULL','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
                 $act_res = mysqli_query($conn, $act_mst) or die( mysqli_error($conn) );
            }
            // account master consignor
            $agent_consignor = "SELECT * FROM  `act_master` WHERE `ac_name` = '".$consignor_name."'";
            $act = mysqli_query($conn, $agent_consignor);
            if (mysqli_num_rows($act) <= 0){
                 $act_code      = accountCode($conn);
                 $act_mstnew = "INSERT INTO `act_master`(`act_code`, `ac_name`, `dr_open_bal`, `cr_open_bal`, `account_group`, `party_code`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`)  VALUES ('".$act_code."','".$consignor_name."','0.00','0.00','SUNDRY DEBTORS','NULL','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
                 
                 $act_qyu = mysqli_query($conn,$act_mstnew) or die( mysqli_error($conn) );

                  
            }
            //account master consignee
            $agent_consignee = "SELECT * FROM  `act_master` WHERE `ac_name` = '".$consignee_name."'";
            $act_data = mysqli_query($conn, $agent_consignee);
            if (mysqli_num_rows($act_data) <= 0){
                 $act_code      = accountCode($conn);
                 $act_mstnewd = "INSERT INTO `act_master`(`act_code`, `ac_name`, `dr_open_bal`, `cr_open_bal`, `account_group`, `party_code`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`)  VALUES ('".$act_code."','".$consignee_name."','0.00','0.00','SUNDRY DEBTORS','NULL','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";

                    $act_qyud = mysqli_query($conn,$act_mstnewd) or die( mysqli_error($conn) );
                
            }


            $consignor_id     = "SELECT * FROM vendor_master WHERE name = '".$consignor_name."' ";
            $consignor_id_res = mysqli_query($conn,$consignor_id);
            $consignor_id_row = mysqli_fetch_assoc($consignor_id_res);

            $consignee_id    = "SELECT * FROM vendor_master WHERE name = '".$consignee_name."' ";
            $consignee_id_res = mysqli_query($conn,$consignee_id);
            $consignee_id_row = mysqli_fetch_assoc($consignee_id_res);
            $insert =  "INSERT INTO `lr_mst`(`lr_type`, `lr_no`, `l_date`, `party_invoice`,
                                            `party_amount`, `truck_no`, `from_place`, `to_place`,
                                            `consignor_name`, `consignee_name`, `billing_to`,
                                            `agent`, `nature_of_goods`, `weight`,`actual_weight`,
                                            `height`,`pcs`,`challan_no`,
                                            `gst_paid_by`, `insured_by`, `billing_party`, `remark`,
                                            `rate_on`, `freight`,`truck_driver_no`, `eway_bill_no`, `packing`,
                                            `charged_weight`, `eway_date`, `eway_ex_date`,
                                            `invoice_date`, `po_no`, `po_date`, `tracking_status`,
                                            `branch_id`, `company_id`,`notes`,
                                            `lorry_type`, `created_id`, `created_datetime`,
                                            `updated_id`, `updated_datetime`, `consignee_address`,
                                            `consignee_city`, `consignee_contact`, `consignee_pan`,
                                            `consignee_gst`,`total_actual_weight`,`total_charged_weight`,`to_be_billed_at`,`lr_mode`,`delivery`,
                                            `st_charges`,`insurance_status`,`policy_no`,`mode`,`insurance_date`)
                                            VALUES ('".$lr_type."','".$lr_no."','".$l_date."',
                                            '".$party_invoice."','".$party_amount."','".$truck_no."'
                                            ,'".$from_place."','".$to_place."',
                                            '".$consignor_id_row['id']."',
                                            '".$consignee_id_row['id']."','".$billing_to."',
                                            '".$agent."','".$description."','".$weight."',
                                            '".$actual_weight."','".$height."',
                                            '".$pcs."','".$challan_no."',
                                            '".$gst_paid_by."','".$insured_by."',
                                            '".$billing_party."','".$remark."','".$rate_on."',
                                            '".$freight."','".$truck_driver_no."','".$eway_bill_no."'
                                            ,'".$packing."','".$charged_weight."','".$eway_date."',
                                            '".$eway_ex_date."','".$invoice_date."','".$po_no."',
                                            '".$po_date."','".$tracking_status."','".$branch_id."',
                                            '".$company_id."','".$notes."',
                                            '".$lorry_type."','".$created_id."',
                                            '".$created_datetime."','".$updated_id."',
                                            '".$updated_datetime."','".$consignee_vendor_address."',
                                            '".$consignee_vendor_city."','".$consignee_vendor_contact."',
                                            '".$consignee_vendor_pan."','".$consignee_vendor_gstin."','".$total_actual_weight."','".$total_charged_weight."','".$to_be_billed_at."','".$lr_mode."','".$delivery."','".$st_charges."','".$insurance_status."','".$policy_no."','".$mode."','".$insurance_date."')"; 

                $result = mysqli_query($conn,$insert);
                $lr_last_id = mysqli_insert_id($conn);
                
                    // Agent exists, insert multiple rows into lr_grid table
                    foreach ($_POST['product'] as $product)
                    {
                        $master_id   = $vendor_last_id;
                        $description = $product['description'];
                        $pcs         = $product['pcs'];
                        $weight      = $product['weight'];
                        $charged_weight      = $product['charged_weight'];
                        $hsn_code            = $product['hsn_code'];
                        $freight_rate        = $product['freight_rate'];
                      

                         $insert_query = "INSERT INTO lr_grid (description, master_id, pcs, weight,charged_weight, hsn_code, freight_rate) 
                                                     VALUES ('$description','$lr_last_id','$pcs',
                                                     '$weight','$charged_weight','$hsn_code','$freight_rate')";
                                                     
                        $insert_result = mysqli_query($conn, $insert_query);
                    }
            
                  $type               = 'lr_add';
                  $user_id            = $_SESSION['user_detail']['id'];
                  $data               = serialize($_POST);
                  $activiti = "INSERT INTO `activities`(`type`, `user_id`, `data`, `created_id`,
                                                        `created_datetime`, `updated_id`,
                                                        `updated_datetime`)
                                                        VALUES ('".$type."','".$user_id."',
                                                        '".$data."','".$created_id."',
                                                        '".$created_datetime."','".$updated_id."',
                                                        '".$updated_datetime."')";
                    $acttivity_res = mysqli_query($conn,$activiti);
                }

                echo json_encode( array('response' => 1, 'msg' => 'DATA SAVED SUCCESSFULLY....!!!', 'alert' => 1, 'redirect' => 'index.php?page=lr/list.php') );die();
            }else{
              echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => BASE_URL . 'index.php?page=lr/add.php') );die();
          }  
      ?>