<?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'];
    $user_acc_no = $_SESSION['user_acc_no'];
}else{
	header('Location: login');
	die();
}

if(isset($_POST['btn_action']))
{
	$dated = date('Y-m-d');
	if($_POST['btn_action']=='save')
	{
$new_dated = $_POST['dated'];
$gst = "OFF";
             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;}
        }
    $due_day = 0;
   
    $statement = $connect->prepare("
     INSERT INTO sale
        (po_no,due_day,branch_id,inv_no,dated,title_id,cust_id,contact,cust_name,inv_type,description,discount,discount_dsc,freight,freight_dsc,gst,gst_pr,fst_pr,ast_pr,user_id,status)
        VALUES (:po_no, :due_day, :branch_id, :inv_no, :dated, :title_id, :cust_id, :contact, :cust_name,  :inv_type, :description, :discount, :discount_dsc, :freight, :freight_dsc, :gst, :gst_pr, :fst_pr, :ast_pr, :user_id, :status)
    ");
    $statement->execute(
      array(
         ':po_no'             =>  0,
         ':due_day'             =>  0,
          ':branch_id'             =>  1,
          ':inv_no'             =>  trim($_POST["inv_no"]),
          ':dated'             =>  $_POST["dated"],
          ':title_id'       =>  2,
          ':cust_id'          =>  1011000,
          ':contact'       =>  $_POST["contact"],
          ':cust_name'       =>  $_POST["cust_name"],
          ':description'       =>  '',
          ':inv_type'       =>  'Cash',
          ':discount'       =>  trim($_POST["discount"]),
          ':discount_dsc'       =>  trim($_POST["discount_dsc"]),             
          ':freight'       =>  trim($_POST["freight"]),
          ':freight_dsc'       =>  trim($_POST["freight_dsc"]),
          ':gst'       =>  $gst,
          ':gst_pr'       => 0,
          ':fst_pr'       =>  0,
          ':ast_pr'       =>  0,
          ':user_id'       =>  $user_id,          
          ':status'       =>  'Active'
          
      )
    );
      
        $statement = $connect->query("SELECT LAST_INSERT_ID()");
         $s_id = $statement->fetchColumn();
       
      for($count=0; $count<$_POST["total_item"]; $count++)
      {
        $statement = $connect->prepare("
          INSERT INTO sale_detail
          (s_id,item_no,store_id,ctn,qty,rate, dis_pr, ln_no)
          VALUES(:s_id, :item_no, :store_id, :ctn, :qty, :rate, :dis_pr, :ln_no)
        ");
        $statement->execute(
          array(
            ':s_id'               =>  $s_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]),
            ':ln_no'        => $count
        
          )
        );
      }    
        $sql ="select sum(qty*rate) from sale_detail where s_id = '".$s_id."'";
        $statement = $connect->prepare($sql);
        $statement->execute();
        $inv_amt = $statement->fetchColumn();     
        $sql ="select sum(rate*dis_pr / 100 * qty) from sale_detail where s_id = '".$s_id."'";
        $statement = $connect->prepare($sql);
        $statement->execute();
        $dis_pr = $statement->fetchColumn();    
      
          $sql = "select discount from sale where s_id = '".$s_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $discount = $statement->fetchColumn();

          $sql = "select freight from sale where s_id = '".$s_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $freight = $statement->fetchColumn();
          $sales = $inv_amt;
        
        
         //  stock_update($connect);          
         
         $others = $freight ;
      
        $sql = "update sale_detail d, items i set d.cost = i.item_cost where d.s_id = '".$s_id."' and d.item_no=i.item_id";
        $statement = $connect->query($sql);
         
         $sql = "select sum(d.qty*d.cost) from sale_detail d where d.s_id = '".$s_id."'";
         $statement = $connect->query($sql);
         $cost = $statement->fetchColumn();
          
          //create jv
         
          $ref_id = $s_id;
         
            $sql = "SELECT IFNULL(max(jv_no),0) FROM jv WHERE branch_id = '".$branch_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            $jv_no++; 
         
          
         
            $inv_no = $_POST["inv_no"];
          
            $sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;
       
       
           
            $source = 'AR Inv';
            $description = 'AR Cash Invoice ' .$s_id .', Inv #: '. $_POST['inv_no'];
      
            $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'          =>  $s_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'              =>  5015002,
            ':debit'          =>  0,
            ':credit'           =>  $sales
            
          )
        );
             $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'          =>  0,
            ':credit'           =>  $cost
            
          )
        );
         $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'          =>  $cost,
            ':credit'           =>  0
            
          )
        );
       
         
         if($others > 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'              =>  2012003,
            ':debit'          =>  0,
            ':credit'           =>  $others
                        
          )
        );
         } 
        if($discount > 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'              =>  3013002,
            ':debit'          =>  $discount,
            ':credit'           =>  0
                        
          )
        );
        
        }
        if($dis_pr > 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'              =>  3013003,
            ':debit'          =>  $dis_pr,
            ':credit'           =>  0
                        
          )
        );
        
        }
        $total_discount = $dis_pr + $discount;

        
        $invoice_total = $sales + $others;
        $receivable = $invoice_total - $total_discount;
        $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'              =>  $user_acc_no,
            ':debit'          =>  $receivable,
            ':credit'           =>  0
                     
          )
        );
        
        /////End Jv/////
      echo 'Success';
    
	}

  if($_POST['btn_action']=='update')
  {
   $gst = 'OFF';
   $cost_up = 0;
    $cost_down = 0;
    $s_id = $_POST['s_id'];
    $ref_id = $s_id;
    $due_day = 0;
   
    $due_date =Date('Y-m-d', strtotime("+".$due_day." days"));
   
      
      $statement = $connect->prepare("
        UPDATE sale
        SET branch_id = :branch_id,
        po_no = :po_no,
        due_day = :due_day,
        inv_no = :inv_no,
        title_id = :title_id,
        dated = :dated,
         due_dated = :due_dated,
        cust_id = :cust_id,
       contact = :contact,
       cust_name = :cust_name,
        description = :description,
        discount = :discount,
         discount_dsc = :discount_dsc, 
            
        freight = :freight,
        freight_dsc = :freight_dsc,
        gst = :gst,
        gst_pr = :gst_pr,
        fst_pr = :fst_pr,
        ast_pr = :ast_pr,
        user_id= :user_id,    
        status = :status        
        WHERE s_id = :s_id
        ");
      $statement->execute(
        array(
          ':branch_id'             =>  $branch_id,
          ':inv_no'             =>  trim($_POST["inv_no"]),
          ':po_no'             =>  '',
          ':title_id'       =>    2,
          ':due_day'             =>  0,
          ':dated'             =>  $_POST["dated"],
          ':due_dated'             =>  $due_date,
          ':cust_id'          =>  1011000,          
          ':contact'       =>  $_POST["contact"],
          ':cust_name'       =>  $_POST["cust_name"],
          ':description'       =>  '',
          ':discount'             =>  trim($_POST["discount"]),
           ':discount_dsc'             =>  trim($_POST["discount_dsc"]),                   
          ':freight'             =>  trim($_POST["freight"]),
          ':freight_dsc'             =>  trim($_POST["freight_dsc"]),
          ':gst'             =>  $gst,
          ':gst_pr'             =>  0,
          ':fst_pr'             =>  0,
          ':ast_pr'             =>  0,
          ':user_id'             =>  $user_id,       
          ':status'             =>  'Active',          
          ':s_id'               =>  $s_id
          )
        );
      
       
         $sql = "delete from sale_detail 
        where s_id = '".$s_id."'";
        $statement = $connect->prepare($sql);
        $statement->execute();
       
      for($count=0; $count<$_POST["total_item"]; $count++)
      {
        $statement = $connect->prepare("
          INSERT INTO sale_detail
          (s_id,item_no,store_id,ctn,qty,rate,dis_pr,ln_no)
          VALUES(:s_id, :item_no, :store_id, :ctn, :qty, :rate, :dis_pr, :ln_no)
        ");
        $statement->execute(
          array(
            ':s_id'               =>  $s_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]),
            ':ln_no'        => $count
        
          )
        );
      }    
    $sql ="select sum(qty*rate) from sale_detail where s_id = '".$s_id."'";
        $statement = $connect->prepare($sql);
        $statement->execute();
        $inv_amt = $statement->fetchColumn();     
        $sql ="select sum(rate*dis_pr / 100 * qty) from sale_detail where s_id = '".$s_id."'";
        $statement = $connect->prepare($sql);
        $statement->execute();
        $dis_pr = $statement->fetchColumn();    
      
          $sql = "select discount from sale where s_id = '".$s_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $discount = $statement->fetchColumn();

          $sql = "select freight from sale where s_id = '".$s_id."'";
          $statement = $connect->prepare($sql);
          $statement->execute();
          $freight = $statement->fetchColumn();
          $sales = $inv_amt;
         
         //  stock_update($connect);          
         
         $others = $freight ;
      
        $sql = "update sale_detail d, items i set d.cost = i.item_cost where d.s_id = '".$s_id."' and d.item_no=i.item_id";
        $statement = $connect->query($sql);
         
         $sql = "select sum(d.qty*d.cost) from sale_detail d where d.s_id = '".$s_id."'";
         $statement = $connect->query($sql);
         $cost = $statement->fetchColumn();
          
          //create jv
         
          $ref_id = $s_id;
         
            $sql = "SELECT IFNULL(max(jv_no),0) FROM jv WHERE branch_id = '".$branch_id."'";
            $statement = $connect->prepare($sql);
            $statement->execute(); 
            $jv_no = $statement->fetchColumn();
            $jv_no++; 
         
          
         
            $inv_no = $_POST["inv_no"];
          
            $sql = "SELECT MAX(jv_no) FROM jv WHERE branch_id = '".$branch_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $jv_no = $statement->fetchColumn();
            settype($jv_no, "integer");
            $jv_no++;
       
       
           
            $source = 'AR Inv';
            $description = 'AR Cash Invoice ' .$s_id .', Inv #: '. $_POST['inv_no'];

            $sql = "select jv_id from jv where source = 'AR Inv' and ref_id = '".$s_id."'";
            $statement = $connect->query($sql);
            $jv_id = $statement->fetchColumn();

        $sql = "update jv set description = '".$description."' where jv_id = '".$jv_id."'";
        $statement = $connect->query($sql);

        $sql = "delete from jv_detail where jv_id = '".$jv_id."'";
        $statement = $connect->query($sql);
        $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'              =>  5015002,
            ':debit'          =>  0,
            ':credit'           =>  $sales
            
          )
        );
             $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'          =>  0,
            ':credit'           =>  $cost
            
          )
        );
         $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'          =>  $cost,
            ':credit'           =>  0
            
          )
        );
      
         
         if($others > 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'              =>  2012003,
            ':debit'          =>  0,
            ':credit'           =>  $others
                        
          )
        );
         } 
        if($discount > 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'              =>  3013002,
            ':debit'          =>  $discount,
            ':credit'           =>  0
                        
          )
        );
        
        }
        if($dis_pr > 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'              =>  3013003,
            ':debit'          =>  $dis_pr,
            ':credit'           =>  0
                        
          )
        );
        
        }
        $total_discount = $dis_pr + $discount;

        
        $invoice_total = $sales + $others;
        $receivable = $invoice_total - $total_discount;
        $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'              =>  $user_acc_no,
            ':debit'          =>  $receivable,
            ':credit'           =>  0
                     
          )
        );
        
      
      
        
        echo 'success';
  }	
	
	if($_POST['btn_action'] == 'delete')
	{
		$s_id = $_POST['s_id'];
		
		$sql = "DELETE FROM sale WHERE s_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
        
        $sql = "DELETE FROM sale_detail WHERE s_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no 
		
		$sql = "SELECT jv_id FROM jv WHERE source = 'AR Inv' and ref_id = '".$s_id."' ";
            $statement = $connect->prepare($sql);
            $statement->execute(); // no need to add `$sql` here, you can take that out
            $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();
            echo 'sale ID: '.$s_id . ' Deleted';
		
		//$result = $statement->fetchAll();	
		
	}
}
?>