<?php
//user_action.php
include('db_con.php');
if (isset($_SESSION['user_id'])) {
		$user_type = $_SESSION['user_type'];
		$user_id = $_SESSION['user_id'];
		$user_name = $_SESSION['user_name'];
		$branch_id = $_SESSION['branch_id'];
		$branch_name = $_SESSION['branch_name'];
		$store_id = $_SESSION['store_id'];
    $store_name = $_SESSION['store_name'];
}else{
	header('Location: login');
	die();
}
if(isset($_POST['btn_action']))
{
	if($_POST['btn_action']=='save')
	{
		$new_dated = $_POST['dated'];
             if($user_type=='user')
             {
            $sql = "select app_value from app_options where app_name='datedown' and user_id = '".$user_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $datedown = $statement->fetchColumn();
            $sql = "select app_value from app_options where app_name='dateup' and user_id = '".$user_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $dateup = $statement->fetchColumn();
             $sql = "SELECT date_sub(curdate(),interval '".$datedown."' day)";
              $statement = $connect->prepare($sql);
              $statement->execute(); // no need to add `$sql` here, you can take that out
              $pre_dated = $statement->fetchColumn();
    if($new_dated < $pre_dated){echo 'Invoice Can not be save in Previous date pre_dated is : '.$pre_dated .' Post Date : '.$new_dated ;return false;}
     $above_dated = Date('Y-m-d', strtotime("+".$dateup .' days'));
    if($new_dated > $above_dated){echo 'Invoice Can not be save in Above date Above dated is :'.$above_dated .' New Date is '. $new_dated;return false;}
        }
    $over_dues = $_POST['over_dues'];
    $pre_balance = $_POST['cur_balance'];
    $due_day = $_POST['due_day'];
   
    $due_dated =Date('Y-m-d', strtotime("+".$due_day." days"));
   
    
   
    $statement = $connect->prepare("
      INSERT INTO sr 
        (po_no,bilty_no,chal_no,emp_id,title_id,dated,due_dated,inv_no,inv_type,inv_of,gst,gst_pr,sm_id,branch_id,cust_id,cust_name,contact,description,discount,discount_dsc, due_day, freight,freight_dsc, pre_balance,over_dues,user_id,status)
        VALUES (:po_no, :bilty_no, :chal_no, :emp_id, :title_id, :dated, :due_dated, :inv_no, :inv_type, :inv_of, :gst,  :gst_pr, :sm_id, :branch_id, :cust_id, :cust_name, :contact, :description, :discount, :discount_dsc, :due_day, :freight, :freight_dsc, :pre_balance, :over_dues, :user_id, :status)
    ");
    $statement->execute(
      array(
          ':po_no'               =>  $_POST["po_no"],
          ':bilty_no'               =>  $_POST["bilty_no"],
          ':chal_no'             =>  $_POST["chal_no"],
          ':emp_id'             =>  $_POST["emp_id"],
          ':title_id'             =>  $_POST["title_id"],
          ':dated'             =>  $_POST["dated"],
          ':due_dated'             =>  $due_dated,
          ':inv_no'             =>  $_POST["inv_no"],
          ':inv_type'             =>  'Credit',
          ':inv_of'             =>  'Wholesale',
           ':gst'             =>  'OFF',
           ':gst_pr'             =>  0,
          ':sm_id'             =>  1,
          ':branch_id'             =>  $branch_id,         
          ':cust_id'       =>  trim($_POST["cust_id"]),
          ':cust_name'       =>  'Credit Customer',
          ':contact'       =>  '',
          ':description'       =>  $_POST["description"],
          ':discount'       =>  trim($_POST["discount"]),
          ':discount_dsc'       =>  trim($_POST["discount_dsc"]),
          ':due_day'       =>  trim($_POST["due_day"]),
          ':freight'       =>  trim($_POST["freight"]),
          ':freight_dsc'       =>  trim($_POST["freight_dsc"]),
           ':pre_balance'       =>  $pre_balance,
            ':over_dues'       =>  $over_dues,
          ':user_id'       =>  $user_id,
          ':status'       =>  'Active'
          
      )
    );
      $statement = $connect->query("SELECT LAST_INSERT_ID()");
      $sr_id = $statement->fetchColumn();
      for($count=0; $count<$_POST["total_item"]; $count++)
      {
        
        $statement = $connect->prepare("
          INSERT INTO sr_detail 
          (sr_id,item_no,store_id,ctn,qty,rate,dis_pr)
          VALUES (:sr_id, :item_no, :store_id, :ctn, :qty, :rate, :dis_pr)
        ");
        $statement->execute(
          array(
            ':sr_id'               =>  $sr_id,
            ':item_no'              =>  trim($_POST["item_no"][$count]),
            ':store_id'              => 1,
            ':ctn'          =>  1,
            ':qty'          =>  trim($_POST["qty"][$count]),
            ':rate'           =>  trim($_POST["rate"][$count]),
            ':dis_pr'           =>  trim($_POST["dis_pr"][$count])
            
          )
        );
      }
 $sql = "update sr_detail d, items i set d.cost = i.item_cost where d.sr_id = '".$sr_id."' and i.item_id=d.item_no";
           $statement = $connect->prepare($sql);
           $statement->execute();
          
        
      
// create jv for sr invoice
    
          
            $sql = "SELECT sum(qty*rate) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $sr = $statement->fetchColumn();
           $sql = "SELECT sum(rate * dis_pr / 100 * qty) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); 
            $dis_pr = $statement->fetchColumn();
             $sr = $sr - $dis_pr;    
            
            $sql = "SELECT sum(qty*cost) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $cost = $statement->fetchColumn();
             $sql = "SELECT gst_pr FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $gst_pr = $statement->fetchColumn();
             $sql = "SELECT freight FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $freight = $statement->fetchColumn();
           
           IF($gst_pr > 0)
           {
           $gst_amount = $sr * $gst_pr / 100;
         }else {$gst_amount = 0;}
            
            $sql = "SELECT sum(qty * dis_rate) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $discount = $statement->fetchColumn();
            if($discount > 0)
            {
              $sr = $sr - $discount;
            }
            $sql = "SELECT discount FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $discount = $statement->fetchColumn();
            
            if($discount > 0)
            {
              $sr = $sr - $discount;
            }
            $sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); 
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;
           
            $source = 'AR InvR';
            $description = 'AR Credit Invoice Return ' .$sr_id .',  ' .$_POST['description'] ;
           
            
            $statement = $connect->prepare("
              INSERT INTO jv 
                (jv_no,branch_id,dated,source,ref_id,description,user_id)
                VALUES (:jv_no, :branch_id, :dated, :source, :ref_id, :description, :user_id)
    ");
    $statement->execute(
      array(
          ':jv_no'             =>  $jv_no,
          ':branch_id'             =>  $branch_id,
          ':dated'             =>  $_POST['dated'],
          ':source'          =>  $source,
          ':ref_id'          =>  $sr_id,
          ':description'       =>  $description,
       
          ':user_id'       =>  $user_id
      )
    );
     $statement = $connect->query("select max(jv_id) from jv");
      $jv_id = $statement->fetchColumn();
      
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  5015001,
            ':debit'          =>  $sr,
            ':credit'           =>  0,
            
          )
        );
        
        
          $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1041004,
            ':debit'          =>  $gst_amount,
            ':credit'           =>  0
                        
          )
        );
        
        
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1041005,
            ':debit'          =>  $freight,
            ':credit'           =>  0
                        
          )
        );
        $Receivable = $sr + $gst_amount + $freight;
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  $_POST['cust_id'],
            ':debit'          =>  0,
            ':credit'           =>  $Receivable
                     
          )
        );
         $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1031006,
            ':debit'          =>  $cost,
            ':credit'           =>  0
                        
          )
        );
       
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  3013001,
            ':debit'          =>  0,
            ':credit'           =>  $cost
                     
          )
        );
        /////End Jv/////
        
      echo 'success';
	}

	if($_POST['btn_action']=='update')
	{
		$sr_id = $_POST['sr_id'];
		$ref_id = $sr_id;
		  $due_day = $_POST['due_day'];
   
    $due_dated =Date('Y-m-d', strtotime("+".$due_day." days"));
      
     
      $statement = $connect->prepare("
                DELETE FROM sr_detail WHERE sr_id = :sr_id
            ");
            $statement->execute(
                array(
                    ':sr_id'       =>      $sr_id
                )
            );
      for($count=0; $count<$_POST["total_item"]; $count++)
      {
      $statement = $connect->prepare("
          INSERT INTO sr_detail 
          (sr_id,item_no,store_id,ctn,qty,rate,dis_pr)
          VALUES (:sr_id, :item_no, :store_id, :ctn, :qty, :rate, :dis_pr)
        ");
        $statement->execute(
          array(
            ':sr_id'               =>  $sr_id,
            ':item_no'              =>  trim($_POST["item_no"][$count]),
            ':store_id'              =>  1,
            ':ctn'          =>  1,
            ':qty'          =>  trim($_POST["qty"][$count]),
            ':rate'           =>  trim($_POST["rate"][$count]),
            ':dis_pr'           =>  trim($_POST["dis_pr"][$count])
                       
          )
        );
        
        //$result = $statement->fetchAll();
      }
      $sql = "update sr_detail d, items i set d.cost = i.item_cost where d.sr_id = '".$sr_id."' and i.item_id=d.item_no";
           $statement = $connect->prepare($sql);
           $statement->execute();
      $statement = $connect->prepare("
        UPDATE sr set
        po_no = :po_no,
        bilty_no = :bilty_no,
        chal_no = :chal_no,
        emp_id = :emp_id,
        title_id = :title_id,
        dated = :dated,
        due_dated = :due_dated,
        inv_no = :inv_no,
        inv_type = :inv_type,
        inv_of = :inv_of,
        sm_id = :sm_id,
        branch_id = :branch_id,
        cust_id = :cust_id,
        cust_name = :cust_name,
        contact = :contact,
        description = :description,
        gst = :gst,
        gst_pr = :gst_pr,
        discount = :discount,
        discount_dsc = :discount_dsc,  
        freight = :freight,
        freight_dsc = :freight_dsc,
        due_day = :due_day,
        pre_balance = :pre_balance,
        over_dues = :over_dues,        
            
        status = :status
        where sr_id = :sr_id         
      ");
      $statement->execute(
        array(
          ':po_no'             =>  $_POST["po_no"],
          ':bilty_no'             =>  $_POST["bilty_no"],
          ':chal_no'             =>  $_POST["chal_no"],
          ':emp_id'             =>  $_POST["emp_id"],
          ':title_id'             =>  $_POST["title_id"],
          ':dated'             =>  $_POST["dated"],          
          ':due_dated'             =>  $due_dated,          
          ':inv_no'             =>  $_POST["inv_no"],
          ':inv_type'             =>  'Credit',
          ':inv_of'          =>  'Wholesale',
          ':sm_id'       =>  1,
          ':branch_id'             =>  $branch_id,
          ':cust_id'             =>  trim($_POST["cust_id"]),          
          ':cust_name'             =>  'Wholesale Customer',
          ':contact'             =>  '',
          ':description'             =>  $_POST["description"],
             ':gst'             => 'OFF',
          ':gst_pr'             =>  0,
          ':discount'             =>  trim($_POST["discount"]),  
          ':discount_dsc'             =>  trim($_POST["discount_dsc"]),  
          ':freight'             =>  trim($_POST["freight"]),  
          ':freight_dsc'             =>  trim($_POST["freight_dsc"]),  
          ':due_day'       =>  trim($_POST["due_day"]),  
           ':pre_balance'       =>  trim($_POST["cur_balance"]),  
            ':over_dues'       =>  trim($_POST["over_dues"]),        
                 
          ':status'               =>  'Active',
          ':sr_id'               =>  $sr_id
        )
      );
     
        /////creating JV//////
// create jv for sr invoice
    
          
            $sql = "SELECT sum(qty*rate) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $sr = $statement->fetchColumn();
                $sql = "SELECT sum(rate * dis_pr / 100 * qty) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); 
            $dis_pr = $statement->fetchColumn();
             $sr = $sr - $dis_pr;              
            $sql = "SELECT sum(qty*cost) FROM sr_detail WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $cost = $statement->fetchColumn();
             $sql = "SELECT gst_pr FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $gst_pr = $statement->fetchColumn();
             $sql = "SELECT freight FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $freight = $statement->fetchColumn();
           
           IF($gst_pr > 0)
           {
           $gst_amount = $sr * $gst_pr / 100;
         }else {$gst_amount = 0;}
            
        
            $sql = "SELECT discount FROM sr WHERE sr_id = '".$sr_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $discount = $statement->fetchColumn();
            
            if($discount > 0)
            {
              $sr = $sr - $discount;
            }
            $sql = "SELECT jv_id FROM jv WHERE source = 'AR InvR' and ref_id = '".$ref_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_id = $statement->fetchColumn();
            $sql = "SELECT jv_no FROM jv WHERE jv_id = '".$jv_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            
               $sql = "SELECT user_id FROM jv WHERE jv_id = '".$jv_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $user_id = $statement->fetchColumn();
               $sql = "SELECT user_acc_no FROM user_detail WHERE user_id = '".$user_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $user_acc_no = $statement->fetchColumn();   
            
            
           
            $source = 'AR InvR';
            $description = 'AR Credit Invoice Return' .$sr_id .', ' .$_POST['description'] ;
           
            
            $statement = $connect->prepare("
        UPDATE jv 
        SET 
        dated = :dated,
        branch_id = :branch_id, 
        source = :source,
        ref_id = :ref_id, 
        description = :description,
             
        user_id = :user_id,
        status = :status
        WHERE jv_id = :jv_id
      ");
            
      
      $statement->execute(
        array(
          ':dated'             =>  $_POST["dated"],
          ':branch_id'          =>  $branch_id,
          ':source'          =>  $source,
          ':ref_id'          =>  $sr_id,
          ':description'       =>  $description,
                      
          ':user_id'       =>  $user_id,
          ':status'       =>  'Active',
          ':jv_id'               =>  $jv_id
        )
      );
        
        $sql = "DELETE FROM jv_detail WHERE jv_id = '".$jv_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
           
       $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  5015003,
            ':debit'          =>  $sr,
            ':credit'           =>  0,
            
          )
        );
        
        
          $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1041004,
            ':debit'          =>  $gst_amount,
            ':credit'           =>  0
                        
          )
        );
        
        
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1041005,
            ':debit'          =>  $freight,
            ':credit'           =>  0
                        
          )
        );
        $Receivable = $sr + $gst_amount + $freight;
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              => $_POST['cust_id'],
            ':debit'          =>  0,
            ':credit'           =>  $Receivable
                     
          )
        );
         $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  1031006,
            ':debit'          =>  $cost,
            ':credit'           =>  0
                        
          )
        );
       
        $statement = $connect->prepare("
          INSERT INTO jv_detail 
          (jv_id,acc_no,debit,credit)
          VALUES(:jv_id, :acc_no, :debit, :credit)
        ");
        $statement->execute(
          array(
            ':jv_id'               =>  $jv_id,
            ':acc_no'              =>  3013001,
            ':debit'          =>  0,
            ':credit'           =>  $cost
                     
          )
        );
        /////End Jv/////
        echo 'success';
	}
	
	if($_POST['btn_action'] == 'delete')
	{

		$s_id = $_POST['sr_id'];
		$sql = "DELETE FROM sr WHERE sr_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute();
        
        $sql = "DELETE FROM sr_detail WHERE sr_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no 
		
		$sql = "SELECT jv_id FROM jv WHERE source = 'AR InvR' and ref_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); 
            $jv_id = $statement->fetchColumn();
            
             $sql = "DELETE FROM jv WHERE jv_id = '".$jv_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute();
            $sql = "DELETE FROM jv_detail WHERE jv_id = '".$jv_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute();
            
		
		$result = $statement->fetchAll();	
		if(isset($result))
		{
			echo 'Deleted ';
		}
		
	}
}
?>