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

  $l_date              = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['lhc_date'])));
  $material_load_date  = mysqli_real_escape_string($conn, date('Y-m-d', strtotime($_POST['material_load_date'])));
  $truck_no            = mysqli_real_escape_string($conn, $_POST['truck_no']);
  $old_truck_no        = mysqli_real_escape_string($conn, $_POST['old_truck_no']);
  $from_place          = mysqli_real_escape_string($conn, $_POST['from_place']);
  $old_from_place      = mysqli_real_escape_string($conn, $_POST['old_from_place']);
  $old_to_place        = mysqli_real_escape_string($conn, $_POST['old_to_place']);
  $to_place            = mysqli_real_escape_string($conn, $_POST['to_place']);
  $agent               = mysqli_real_escape_string($conn, $_POST['agent']);
  $lorry_type          = mysqli_real_escape_string($conn, $_POST['lorry_type']);
  $chasis_no           = mysqli_real_escape_string($conn, $_POST['chasis_no']);
  $engine_no           = mysqli_real_escape_string($conn, $_POST['engine_no']);
  $permit_no           = mysqli_real_escape_string($conn, $_POST['permit_no']);
  $p_from              = mysqli_real_escape_string($conn, $_POST['p_from']);
  $up_to               = mysqli_real_escape_string($conn, $_POST['up_to']);
  $insurance_no        = mysqli_real_escape_string($conn, $_POST['insurance_no']);
  $branch              = mysqli_real_escape_string($conn, $_POST['branch']);
  $policy_no           = mysqli_real_escape_string($conn, $_POST['policy_no']);
  $p_up_to             = mysqli_real_escape_string($conn, $_POST['p_up_to']);
  $d_name              = mysqli_real_escape_string($conn, $_POST['d_name']);
  $d_address           = mysqli_real_escape_string($conn, $_POST['d_address']);
  $lic_no              = mysqli_real_escape_string($conn, $_POST['lic_no']);
  $date                = date('Y-m-d', strtotime(mysqli_real_escape_string($conn, $_POST['date'])));
  $issued_from         = mysqli_real_escape_string($conn, $_POST['issued_from']);
  $mobile              = mysqli_real_escape_string($conn, $_POST['mobile']);
  $owner_name          = mysqli_real_escape_string($conn, $_POST['owner_name']);
  $owner_address       = mysqli_real_escape_string($conn, $_POST['owner_address']);
  $pan_no              = mysqli_real_escape_string($conn, $_POST['pan_no']);
  $disel_amnt          = mysqli_real_escape_string($conn, $_POST['disel_amnt']);
  $o_mobile            = mysqli_real_escape_string($conn, $_POST['o_mobile']);
  $lorry_hire          = mysqli_real_escape_string($conn, $_POST['lorry_hire']);
 	$balance             = mysqli_real_escape_string($conn, $_POST['balance']);
  $net_amnt            = mysqli_real_escape_string($conn, $_POST['net_amnt']);
  $payment_mode        = mysqli_real_escape_string($conn, $_POST['payment_mode']);
  $payment_to          = mysqli_real_escape_string($conn, $_POST['payment_to']);
  $cash                = mysqli_real_escape_string($conn, $_POST['cash']);
  
  $subs = $_POST['sub'];
  $less_amount = '';
  if(count($subs) > 0) {
    foreach ($subs as $sub_key => $sub) {
      if($sub['amount'] > 0 ) {
        $less_amount = $less_amount +$sub['amount'];
      }
    }
  }      
  $ledger_net_amount   = mysqli_real_escape_string($conn, $_POST['net_amnt'] - $less_amount);

  if(!empty($_POST['rate_on'])){
    $rate_on     = mysqli_real_escape_string($conn, $_POST['rate_on']);
  }else{
    $rate_on     = '';
  }

  if(!empty($_POST['rate'])){
    $rate     = mysqli_real_escape_string($conn, $_POST['rate']);
  }else{
    $rate     = '';
  }

  if(!empty($_POST['payment_type'])){
    $payment_type        = mysqli_real_escape_string($conn, implode(",", $_POST['payment_type']));
  }else{
    $payment_type = '';
  }

  $pay_mode_amnt       = mysqli_real_escape_string($conn, $_POST['pay_mode_amnt']);
  
  if(!empty($_POST['cash'])){
    $total_cash_amnt     = mysqli_real_escape_string($conn, $_POST['cash']);
  }else{
    $total_cash_amnt = '';
  }

  if(!empty($_POST['pay_mode_amnt'])){
    $total_bank_amnt     = mysqli_real_escape_string($conn, $_POST['pay_mode_amnt']);
  }else{
    $total_bank_amnt     = '';
  }

  if(!empty($_POST['imps_number'])){
    $imps_number         = mysqli_real_escape_string($conn, $_POST['imps_number']);
  }else{
    $imps_number         = '';
  }

  if(!empty($_POST['neft_number'])){
    $neft_number         = mysqli_real_escape_string($conn, $_POST['neft_number']);
  }else{
    $neft_number         = '';
  }

  if(!empty($_POST['rtgs_number'])){
    $rtgs_number         = mysqli_real_escape_string($conn, $_POST['rtgs_number']);
  }else{
    $rtgs_number         = '';
  }

  if(!empty($_POST['cheque_number'])){
    $cheque_number         = mysqli_real_escape_string($conn, $_POST['cheque_number']);
  }else{
    $cheque_number         = '';
  }  

  if(!empty($_POST['cheque_date'])){
    $cheque_date         = date('Y-m-d', strtotime(mysqli_real_escape_string($conn, $_POST['cheque_date'])));
  }else{
    $cheque_date         = '';
  }  

  if(!empty($_POST['lhc_date'])){
    $payment_date  = date('Y-m-d', strtotime(mysqli_real_escape_string($conn, $_POST['lhc_date'])));
  }else{
    $payment_date  = '';
  }

  if($_POST['old_image'] != ''){
    if($_FILES["image"]["name"] != ''){
        $rc_front_image = '';
        if($_FILES["image"]["name"] != ''){
            $rc_front_file_extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
            if (!in_array($rc_front_file_extension, $config['attachment']['valid_types'])) {
                echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
                        die();
            }else if ($config['attachment']['file_size'] < $_FILES["image"]["size"]) {
                echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
                    die();
            }
            $image = rand(1,99999).'.'.basename($_FILES['image']['name']);
            $rc_front_upload_file_path= $config['attachment']['lhc_folder_path'] . $image;
            @move_uploaded_file($_FILES["image"]["tmp_name"], $rc_front_upload_file_path);
            $rc_front_image = $image;
        }
    }else{
      $image  = $_POST['old_image'];    
    }
  }else{
    $rc_front_image = '';
    if($_FILES["image"]["name"] != ''){
      $rc_front_file_extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
      if (!in_array($rc_front_file_extension, $config['attachment']['valid_types'])) {
          echo json_encode( array('response' => 2, 'msg' => 'The file type is not allowed to upload. Please try again !!', 'alert' => 1));
                  die();
      }else if ($config['attachment']['file_size'] < $_FILES["image"]["size"]) {
          echo json_encode( array('response' => 2, 'msg' => 'The file is to big to upload. !!', 'alert' => 1));
              die();
      }
      $image             = rand(1,99999).'.'.basename($_FILES['image']['name']);

      $rc_front_upload_file_path= $config['attachment']['lhc_folder_path'] . $image;
      @move_uploaded_file($_FILES["image"]["tmp_name"], $rc_front_upload_file_path);
      $rc_front_image = $image;
    }
  }
  
  $adv_amnt             = mysqli_real_escape_string($conn, $_POST['adv_amnt']);
  $other_add            = mysqli_real_escape_string($conn, $_POST['other_add']);
  $other_less           = mysqli_real_escape_string($conn, $_POST['other_less']);
  $total_del            = mysqli_real_escape_string($conn, $_POST['total_del']);
  $bank_name            = mysqli_real_escape_string($conn, $_POST['bank_name']);
  $cash_name            = mysqli_real_escape_string($conn, $_POST['cash_name']);
  $products             = $_POST['product'];
  $expense              = $_POST['expense'];
  
  $company_id           = $_SESSION['company_id'];
  $branch_id            = $_SESSION['branch_id'];
  $created_datetime     = risFormatDate($_POST['lhc_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'];

if($_POST["id"] == ''){
  if($payment_to == 'AGENT'){
    $act_msetr  = "SELECT * FROM `act_master` WHERE `ac_name` = '".$agent."'";
    $act_ma_res = mysqli_query($conn,$act_msetr);
    $act_ma_row = mysqli_fetch_array($act_ma_res);
  }else{
    $tr_mst = "SELECT * FROM `truck_mst` WHERE `id` = '".$owner_name."'";
    $tr_mst_res = mysqli_query($conn,$tr_mst);
    $tr_mst_row = mysqli_fetch_array($tr_mst_res);

    $act_msetr  = "SELECT * FROM `act_master` WHERE `ac_name` = '".$tr_mst_row['o_name']."'";
    $act_ma_res = mysqli_query($conn,$act_msetr);
    $act_ma_row = mysqli_fetch_array($act_ma_res);
  }

  foreach ($products as $product) {
    if( isset($product['lr_no']) && !empty($product['lr_no']) ) {
      $type                = 'lhc_add';
      $user_id             = $_SESSION['user_detail']['id'];
      $data                = serialize($_POST);
    
      $insert = "INSERT INTO `lhc`(`lhc_no`, `lhc_date`, `material_load_date`, `truck_no`, `lr_no`, `pkgs`, `content`, `weight`, `from_place`, `to_place`, `agent`, `lorry_type`, `chasis_no`, `engine_no`, `permit_no`, `p_from`, `up_to`, `insurance_no`, `branch`, `policy_no`, `p_up_to`, `d_name`, `d_address`, `lic_no`, `date`, `issued_from`, `mobile`, `owner_name`, `owner_address`, `pan_no`, `o_mobile`, `rate_on`, `rate`, `lorry_hire`, `adv_amnt`, `balance`, `net_amnt`, `payment_mode`, `cash_name`, `cash`, `payment_type`, `payment_to`, `pay_mode_amnt`, `disel_amnt`,`imps_number`, `rtgs_number`, `neft_number`, `cheque_number`, `cheque_date`, `bank_name`, `payment_date`, `image`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$l_date."','".$product['lr_date']."','".$truck_no."','".$product['lr_no']."','".$product['pkgs']."','".$product['content']."','".$product['weight']."','".$from_place."','".$to_place."','".$agent."','".$lorry_type."','".$chasis_no."','".$engine_no."','".$permit_no."','".$p_from."','".$up_to."','".$insurance_no."','".$branch."','".$policy_no."','".$p_up_to."','".$d_name."','".$d_address."','".$lic_no."','".$date."','".$issued_from."','".$mobile."','".$owner_name."','".$owner_address."','".$pan_no."','".$o_mobile."','".$rate_on."','".$rate."','".$lorry_hire."','".$adv_amnt."','".$balance."','".$net_amnt."','".$payment_mode."','".$cash_name."','".$cash."','".$payment_type."','".$payment_to."','".$pay_mode_amnt."','".$disel_amnt."','".$imps_number."','".$rtgs_number."','".$neft_number."','".$cheque_number."','".$cheque_date."','".$bank_name."','".$payment_date."','".$image."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";


      $result = mysqli_query($conn,$insert);
      $lhc_id = mysqli_insert_id($conn);
      if($truck_no != $old_truck_no){
        $truck_change_msg = 'Truck changed from ' . $old_truck_no . ' to ' . $truck_no ;
        
        $th = "INSERT INTO `lhc_change_truck_history`(`lhc_id`, `lhc_no`, `old_truck_no`, `new_truck_no`, `old_from_place`, `new_from_place`, `old_to_place`, `new_to_place`, `description`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_id."','".$lhc_no."','".$old_truck_no."','".$truck_no."','".$old_from_place."','".$from_place."','".$old_to_place."','".$to_place."','".$truck_change_msg."','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
        $th_res = mysqli_query($conn,$th);
      }

      $update = "UPDATE `lr_mst` SET `lhc_status`='Y' WHERE lr_no = '".$product['lr_no']."' AND `branch_id`='".$branch_id."' AND `company_id`='".$company_id."'";
      $update_res = mysqli_query($conn,$update);

    }
  }

  // LORRY HIRE
  $master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
  $ac       = "SELECT * FROM account_control WHERE descr = 'LHC'";
  $ac_res   = mysqli_query($conn,$ac);
  $ac_rows  = mysqli_fetch_assoc($ac_res);
  $act_code = @$master_accounts[$ac_rows['account_group']];
  $lr = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$l_date."','P','".$act_ma_row['act_code']."','".$act_code."','".$lorry_hire."','','','','".$ledger_net_amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
  $lr_res = mysqli_query($conn,$lr);

  // ADDITION
  $adds = $_POST['add'];
  if(count($adds) > 0) {
    foreach ($adds as $add_key => $add) {
      if($add['tax_mst_id'] > 0 && $add['amount'] > 0 ) {
        $lhc_details = "INSERT INTO `lhc_details`(`lhc_id`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$branch_id."','".$company_id."')";
        $lhc_del_res = mysqli_query($conn,$lhc_details);

        // GENERAL LEDGER
        $get_tax       = "SELECT * FROM `tax_mst` WHERE `id` = '".$add['tax_mst_id']."'";
        $get_tax_res   = mysqli_query($conn,$get_tax);
        $get_tax_row   = mysqli_fetch_array($get_tax_res);
        $ac_id         = $get_tax_row['account_group'];

        $acc_name      = "SELECT * FROM `act_master` WHERE `id` = '".$ac_id."'";
        $acc_name_res  = mysqli_query($conn,$acc_name);
        $acc_name_row  = mysqli_fetch_array($acc_name_res);
              
        $add_two = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$act_ma_row['act_code']."','".$acc_name_row['act_code']."','".$add['amount']."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
        $add_one_res = mysqli_query($conn,$add_two);
      }
    }
  }

  // DEDUCTION
  $subs = $_POST['sub'];
  $tds_amnt = '';
  if(count($subs) > 0) {
    foreach ($subs as $sub_key => $sub) {
      if($sub['tax_mst_id'] > 0 && $sub['amount'] > 0 ) {
        $lhc_details = "INSERT INTO `lhc_details`(`lhc_id`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','sub','". $sub_key ."','".$sub['tax_mst_id']."','".$sub['amount']."','".$branch_id."','".$company_id."')";
        $lhc_del_res = mysqli_query($conn,$lhc_details);

        $tax     = "select * from tax_mst WHERE sign = '-' AND FIND_IN_SET('LHC', module)";
        $tax_res = mysqli_query($conn,$tax);
        while ($tax_row = mysqli_fetch_array($tax_res)) {
          $tax_name = $tax_row['id'];
          $account  = $tax_row['account_group'];

          if($sub['tax_mst_id'] == $tax_name){
            $tds_amnt = $sub['amount'];
            $act_tds     = "select * from act_master where id = '".$account."'";
            $act_tds_res = mysqli_query($conn,$act_tds);
            $act_tds_row = mysqli_fetch_array($act_tds_res);

            $tds_am = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$act_tds_row['act_code']."','".$act_ma_row['act_code']."','".$tds_amnt."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            $tds_am_res = mysqli_query($conn,$tds_am);

            $trans = "INSERT INTO `trans`(`voucher_no`, `voucher_date`, `act_code`, `amount`, `adjust`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `flag`, `mark`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','".$act_ma_row['act_code']."','".$net_amnt."','".$total_del."','".$balance."','','','".$other_add."','".$other_less."','LHC','','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            $trans_res = mysqli_query($conn,$trans);

            //TRANS LAST ID

            $last_id = mysqli_insert_id($conn);
            $trans_det = "INSERT INTO `trans_details`(`voucher_no`, `trans_id`, `adjust`, `flag`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','".$last_id."','".$total_del."','LHC','".$balance."','','','".$other_add."','".$other_less."','".$branch_id."','".$company_id."')";
            $trans_det_res = mysqli_query($conn,$trans_det);

          }else{
            $tds_amnt = '';
          }
        }
      }
    }
  }
  $tds_amnt;

  //EXPENSE
  if(count($expense) > 0){
    foreach ($expense as $key => $expences) {
      if( isset($expences['account_id']) && !empty($expences['account_id']) ) {
        $save_data = mysqli_query($conn, "INSERT INTO `lhc_expense_details`(`lhc_no`, `account_name`, `account_code`, `account_id`, `amount`) VALUES ('".$lhc_no."','".$expences['account_name']."','".$expences['account_code']."','".$expences['account_id']."','".$expences['amount']."')");

        $gl = mysqli_query($conn, "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$expences['account_code']."','".$act_code."','".$expences['amount']."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')");
      }
    }
  }
  // activity log
  $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{
  // update
  if($payment_to == 'AGENT'){
    $act_msetr  = "SELECT * FROM `act_master` WHERE `ac_name` = '".$agent."'";
    $act_ma_res = mysqli_query($conn,$act_msetr);
    $act_ma_row = mysqli_fetch_array($act_ma_res);
  }else{
    $tr_mst = "SELECT * FROM `truck_mst` WHERE `id` = '".$owner_name."'";
    $tr_mst_res = mysqli_query($conn,$tr_mst);
    $tr_mst_row = mysqli_fetch_array($tr_mst_res);
    
    $act_msetr  = "SELECT * FROM `act_master` WHERE `ac_name` = '".$tr_mst_row['o_name']."'";
    $act_ma_res = mysqli_query($conn,$act_msetr);
    $act_ma_row = mysqli_fetch_array($act_ma_res);
  }
  
  // DATA NEW INSERTED 
  $delete_gl = mysqli_query($conn, "DELETE FROM `general_ledger` WHERE `voucher_no` = '".$lhc_no."' AND `flag` = 'P'");

  $delete_gl = mysqli_query($conn, "DELETE FROM `general_ledger` WHERE `voucher_no` = '".$lhc_no."' AND `flag` = 'G' AND mark = 'P'");

  $lps = mysqli_query($conn, "SELECT * FROM `lhc_payment_status` WHERE `lhc_no` = '".$lhc_no."' AND flag is null");
  while ($lps_row = mysqli_fetch_assoc($lps)) {

    //DELETE GENERAL LEDGER
    $delete_lpd = mysqli_query($conn, "DELETE FROM `lhc_payment_status` WHERE `voucher_no` = '".$lps_row['voucher_no']."' AND flag is null");
  }

  $delete_add = mysqli_query($conn, "DELETE FROM `lhc_details` WHERE `lhc_id` = '".$lhc_no."'");
  $expense_delete = mysqli_query($conn, "DELETE FROM `lhc_expense_details` WHERE `lhc_no` = '".$lhc_no."'");

  if( count($products) > 0) {
    $success = false;
    $temp_lhc = array();
    foreach ($products as $product) {
      if( !empty($product['lr_no'])) {
        if( isset($product['auto_inc_id']) && !empty($product['auto_inc_id']) && $product['auto_inc_id'] > 0 ) {
          
          $type       = 'lhc_update';
          $user_id    = $_SESSION['user_detail']['id'];
          $data       = serialize($_POST);
          $items[]    = $product['auto_inc_id'];
          $temp_lhc[] = $product['lr_no'];
          $update = "UPDATE `lhc` SET `lhc_date`='".$l_date."',`material_load_date`='".$material_load_date."',`truck_no`='".$truck_no."',`lr_no`='".$product['lr_no']."',`pkgs`='".$product['pkgs']."',`content`='".$product['content']."',`weight`='".$product['weight']."',`from_place`='".$from_place."',`to_place`='".$to_place."',`agent`='".$agent."',`lorry_type`='".$lorry_type."',`chasis_no`='".$chasis_no."',`engine_no`='".$engine_no."',`permit_no`='".$permit_no."',`p_from`='".$p_from."',`up_to`='".$up_to."',`insurance_no`='".$insurance_no."',`branch`='".$branch."',`policy_no`='".$policy_no."',`p_up_to`='".$p_up_to."',`d_name`='".$d_name."',`d_address`='".$d_address."',`lic_no`='".$lic_no."',`date`='".$date."',`issued_from`='".$issued_from."',`mobile`='".$mobile."',`owner_name`='".$owner_name."',`owner_address`='".$owner_address."',`pan_no`='".$pan_no."',`o_mobile`='".$o_mobile."',`lorry_hire`='".$lorry_hire."',`adv_amnt`='".$adv_amnt."',`balance`='".$balance."',`net_amnt`='".$net_amnt."',`payment_mode`='".$payment_mode."',`cash`='".$total_cash_amnt."',`payment_type`='".$payment_type."',`payment_to`='".$payment_to."',`pay_mode_amnt`='".$total_bank_amnt."',`disel_amnt`='".$disel_amnt."',`imps_number`='".$imps_number."',`rtgs_number`='".$rtgs_number."',`neft_number`='".$neft_number."',`cheque_number`='".$cheque_number."',`cheque_date`='".$cheque_date."',`bank_name`='".$bank_name."',`payment_date`='".$payment_date."',`image`='".$image."',`company_id`='".$company_id."',`branch_id`='".$branch_id."',`updated_id`='".$updated_id."',`updated_datetime`='".$updated_datetime."' WHERE `id`='".$product['auto_inc_id']."' AND `branch_id`='".$_SESSION['branch_id']."' AND `company_id`='".$_SESSION['company_id']."'";
          $result = mysqli_query($conn,$update);
          $lhc_id = $_POST['last_lhc_id'];
          if($truck_no != $old_truck_no){
            $truck_change_msg = 'Truck changed from ' . $old_truck_no . ' to ' . $truck_no ;
            
            $th = "INSERT INTO `lhc_change_truck_history`(`lhc_id`, `lhc_no`, `old_truck_no`, `new_truck_no`, `old_from_place`, `new_from_place`, `old_to_place`, `new_to_place`, `description`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_id."','".$lhc_no."','".$old_truck_no."','".$truck_no."','".$old_from_place."','".$from_place."','".$old_to_place."','".$to_place."','".$truck_change_msg."','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            $th_res = mysqli_query($conn,$th);
          }
      
          $update = "UPDATE `lr_mst` SET `lhc_status`='Y' WHERE lr_no = '".$product['lr_no']."' AND `branch_id` = '".$branch_id."' AND `company_id` = '".$company_id."'";
          $update_res = mysqli_query($conn,$update);
          
          $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);
          $success = true;
        }else{
            $temp_lhc[] = $product['lr_no'];
            $new_lhc = "INSERT INTO `lhc`(`lhc_no`, `lhc_date`, `material_load_date`, `truck_no`, `lr_no`, `pkgs`, `content`, `weight`, `from_place`, `to_place`, `agent`, `lorry_type`, `chasis_no`, `engine_no`, `permit_no`, `p_from`, `up_to`, `insurance_no`, `branch`, `policy_no`, `p_up_to`, `d_name`, `d_address`, `lic_no`, `date`, `issued_from`, `mobile`, `owner_name`, `owner_address`, `pan_no`, `o_mobile`, `lorry_hire`, `adv_amnt`, `balance`, `net_amnt`, `payment_mode`, `cash_name`, `cash`, `payment_type`, `payment_to`, `pay_mode_amnt`, `disel_amnt`,`imps_number`, `rtgs_number`, `neft_number`, `cheque_number`, `cheque_date`, `bank_name`, `payment_date`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$l_date."','".$material_load_date."','".$truck_no."','".$product['lr_no']."','".$product['pkgs']."','".$product['content']."','".$product['weight']."','".$from_place."','".$to_place."','".$agent."','".$lorry_type."','".$chasis_no."','".$engine_no."','".$permit_no."','".$p_from."','".$up_to."','".$insurance_no."','".$branch."','".$policy_no."','".$p_up_to."','".$d_name."','".$d_address."','".$lic_no."','".$date."','".$issued_from."','".$mobile."','".$owner_name."','".$owner_address."','".$pan_no."','".$o_mobile."','".$lorry_hire."','".$adv_amnt."','".$balance."','".$net_amnt."','".$payment_mode."','".$cash_name."','".$cash."','".$payment_type."','".$payment_to."','".$pay_mode_amnt."','".$disel_amnt."','".$imps_number."','".$rtgs_number."','".$neft_number."','".$cheque_number."','".$cheque_date."','".$bank_name."','".$payment_date."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";

            $result       = mysqli_query($conn,$new_lhc) or die(mysqli_error($conn));
            $items[]      = mysqli_insert_id($conn);
            $success      = true;
        }
      }
    }    

    $lhc_data     = "SELECT * FROM lhc WHERE `lhc_no` = '".$lhc_no."' AND `branch_id` = '".$branch_id."' AND `company_id` = '".$company_id."'";
    $lhc_data_res = mysqli_query($conn,$lhc_data);
    $lhc_datas = array();
    while ($lhc_data_row = mysqli_fetch_assoc($lhc_data_res)) {
      $lhc_datas[] = $lhc_data_row['lr_no'];
    }

    $get_diff_lr    = array_diff($lhc_datas,$temp_lhc);
    $delete_lhc     = "DELETE FROM `lhc` WHERE `lr_no` IN ('" . implode("','", $get_diff_lr) . "') AND `branch_id` = '".$branch_id."' AND `company_id` = '".$company_id."'";

    $delete_lhc_res = mysqli_query($conn,$delete_lhc);
    $update_lr      = "UPDATE `lr_mst` SET `lhc_status`='N' WHERE `lr_no` IN ('" . implode("','", $get_diff_lr) . "') AND `branch_id` = '".$branch_id."' AND `company_id` = '".$company_id."'";
    $lr_res         = mysqli_query($conn,$update_lr);
  }
  

  // LORRY HIRE
  $master_accounts       = combine(getAllRecords('act_master'), 'id', 'act_code');
  $ac       = "SELECT * FROM account_control WHERE descr = 'LHC'";
  $ac_res   = mysqli_query($conn,$ac);
  $ac_rows  = mysqli_fetch_assoc($ac_res);
  $act_code = @$master_accounts[$ac_rows['account_group']];

  $lr = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','P','".$act_ma_row['act_code']."','".$act_code."','".$lorry_hire."','','','','".$ledger_net_amount."','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
  $lr_res = mysqli_query($conn,$lr);

  // ADDITION
  $adds = $_POST['add'];
  if(count($adds) > 0) {
    foreach ($adds as $add_key => $add) {
      if($add['tax_mst_id'] > 0 && $add['amount'] > 0 ) {
        $lhc_details = "INSERT INTO `lhc_details`(`lhc_id`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','add','". $add_key ."','".$add['tax_mst_id']."','".$add['amount']."','".$branch_id."','".$company_id."')";
        $lhc_del_res = mysqli_query($conn,$lhc_details);

        // GENERAL LEDGER
        $get_tax       = "SELECT * FROM `tax_mst` WHERE `id` = '".$add['tax_mst_id']."'";
        $get_tax_res   = mysqli_query($conn,$get_tax);
        $get_tax_row   = mysqli_fetch_array($get_tax_res);
        $ac_id         = $get_tax_row['account_group'];

        $acc_name      = "SELECT * FROM `act_master` WHERE `id` = '".$ac_id."'";
        $acc_name_res  = mysqli_query($conn,$acc_name);
        $acc_name_row  = mysqli_fetch_array($acc_name_res);
              
        $add_two = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$act_ma_row['act_code']."','".$acc_name_row['act_code']."','".$add['amount']."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
        $add_one_res = mysqli_query($conn,$add_two);
      }
    }
  }

  // DEDUCTION
  $subs = $_POST['sub'];
  $tds_amnt = '';
  if(count($subs) > 0) {
    foreach ($subs as $sub_key => $sub) {
      if($sub['tax_mst_id'] > 0 && $sub['amount'] > 0 ) {
        $lhc_details = "INSERT INTO `lhc_details`(`lhc_id`, `type`, `key`, `tax_mst_id`, `amount`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','sub','". $sub_key ."','".$sub['tax_mst_id']."','".$sub['amount']."','".$branch_id."','".$company_id."')";
        $lhc_del_res = mysqli_query($conn,$lhc_details);

        $tax     = "select * from tax_mst WHERE sign = '-' AND FIND_IN_SET('LHC', module)";
        $tax_res = mysqli_query($conn,$tax);
        while ($tax_row = mysqli_fetch_array($tax_res)) {
          $tax_name = $tax_row['id'];
          $account  = $tax_row['account_group'];

          if($sub['tax_mst_id'] == $tax_name){
            $tds_amnt = $sub['amount'];
            $act_tds     = "select * from act_master where id = '".$account."'";
            $act_tds_res = mysqli_query($conn,$act_tds);
            $act_tds_row = mysqli_fetch_array($act_tds_res);

            $tds_am = "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$act_tds_row['act_code']."','".$act_ma_row['act_code']."','".$tds_amnt."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            $tds_am_res = mysqli_query($conn,$tds_am);

            $trans = "INSERT INTO `trans`(`voucher_no`, `voucher_date`, `act_code`, `amount`, `adjust`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `flag`, `mark`, `branch_id`, `company_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','".$act_ma_row['act_code']."','".$net_amnt."','".$total_del."','".$balance."','','','".$other_add."','".$other_less."','LHC','','".$branch_id."','".$company_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')";
            $trans_res = mysqli_query($conn,$trans);

            //TRANS LAST ID

            $last_id = mysqli_insert_id($conn);
            $trans_det = "INSERT INTO `trans_details`(`voucher_no`, `trans_id`, `adjust`, `flag`, `balance`, `discount`, `tds`, `other_add`, `other_less`, `branch_id`, `company_id`) VALUES ('".$lhc_no."','".$last_id."','".$total_del."','LHC','".$balance."','','','".$other_add."','".$other_less."','".$branch_id."','".$company_id."')";
            $trans_det_res = mysqli_query($conn,$trans_det);

          }else{
            $tds_amnt = '';
          }
        }
      }
    }
  }
  $tds_amnt;
  

  //EXPENSE
  if(count($expense) > 0){
    foreach ($expense as $key => $expences) {
      if( isset($expences['account_id']) && !empty($expences['account_id']) ) {
        $save_data = mysqli_query($conn, "INSERT INTO `lhc_expense_details`(`lhc_no`, `account_name`, `account_code`, `account_id`, `amount`) VALUES ('".$lhc_no."','".$expences['account_name']."','".$expences['account_code']."','".$expences['account_id']."','".$expences['amount']."')");

        $gl = mysqli_query($conn, "INSERT INTO `general_ledger`(`voucher_no`, `voucher_date`, `flag`, `credit_account`, `debit_account`, `amount`, `remark`, `checked`, `mark`, `net_amount`, `company_id`, `branch_id`, `created_id`, `created_datetime`, `updated_id`, `updated_datetime`) VALUES ('".$lhc_no."','".$payment_date."','G','".$expences['account_code']."','".$act_code."','".$expences['amount']."','','','P','0','".$company_id."','".$branch_id."','".$created_id."','".$created_datetime."','".$updated_id."','".$updated_datetime."')");
      }
    }
  }
}
  echo json_encode( array('response' => 1, 'msg' => 'DATA SAVED SUCCESSFULLY....!!!', 'alert' => 1, 'redirect' => 'index.php?page=lhc/list.php') );die();
}else{
   echo json_encode( array('response' => 2, 'msg' => 'Opps', 'alert' => 1, 'redirect' => 'index.php?page=lhc/add.php') );die();
}
?>