<?php 
ob_start();
session_start();
include "../config/config.php";
include "../config/session.php";



if(isset($_POST['type']) && $_POST['type']=='add_sales_payment'){
    
     try{
         
        $pdo->beginTransaction(); 
        
        
        
        $sale_id = (isset($_POST['sale_id'])) ? $_POST['sale_id'] : "";
        $grand_total = (isset($_POST['grand_total'])) ? $_POST['grand_total'] : "";
        $paid_amount = (isset($_POST['paid_amount'])) ? $_POST['paid_amount'] : "";
        $payment_type = (isset($_POST['payment_type'])) ? $_POST['payment_type'] : "";
        $reference = (isset($_POST['reference'])) ? $_POST['reference'] : "";
        $notes = (isset($_POST['notes'])) ? $_POST['notes'] : "";
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        
        $db_paid_amount = (isset($_POST['db_paid'])) ? $_POST['db_paid'] : "";
        $discount_amount = 0;
        
        
        $type = "Credit";
        $accounts = 1;
        $customer_id = 0;
        $account_id =0;
        $balance = $grand_total-$db_paid_amount;
        
        
   
        
        
        if($paid_amount!=0){
        
    
            
        
            
            
            $statement = $pdo->prepare("UPDATE `tbl_sales` SET `paid`=paid+'$paid_amount' WHERE id=?");
            $result = $statement->execute(array($sale_id)); 
                        
            
            
           if($result)
           {
               
               $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`, `discount`, `sale_id`, `customer_id`, 
               `scheme_id`, `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`) VALUES (?,?,?,?,?,?,
               ?,?,?,?,?,?,?)");
               $result = $statement->execute(array($payment_date, $type, $paid_amount, $discount_amount, $sale_id, $customer_id,
               $account_id, $accounts, $payment_type, $reference, $today_date, $session_id, $notes)); 

                
              
               
                $pdo->commit();
                
                $return_arr['message']='Payment Added Successfully...';
                $return_arr['status']=200;
           } }
           else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
            
            
             
     }catch(PDOException $e){
         $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}



if(isset($_POST['type']) && $_POST['type']=='add_purchase_payment'){
    
     try{
         
        $pdo->beginTransaction(); 
        
        
        
        $purchase_id = (isset($_POST['purchase_id'])) ? $_POST['purchase_id'] : "";
        $grand_total = (isset($_POST['grand_total'])) ? $_POST['grand_total'] : "";
        $paid_amount = (isset($_POST['paid_amount'])) ? $_POST['paid_amount'] : "";
        $payment_type = (isset($_POST['payment_type'])) ? $_POST['payment_type'] : "";
        $reference = (isset($_POST['reference'])) ? $_POST['reference'] : "";
        $notes = (isset($_POST['notes'])) ? $_POST['notes'] : "";
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        
        $db_paid_amount = (isset($_POST['db_paid'])) ? $_POST['db_paid'] : "";
        
        $metal_weight = (isset($_POST['weight'])) ? $_POST['weight'] : "0";
        $metal_rate = (isset($_POST['rate'])) ? $_POST['rate'] : "";
        
        $type = "Debit";
        $accounts = 2;
        $customer_id = 0;
        $account_id =0;
        $balance = $grand_total-$db_paid_amount;
        
        
        if($discount_amount==""){
            $discount_amount=0;
        }
        
        
        
    $statement = $pdo->prepare("SELECT * FROM tbl_purchases e where e.id=?");
    $statement->execute(array($purchase_id));
    $emp_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData==1){
        $supplier_id = $emp_data[0]['supplier_id'];
    }
        
        
        
        
        
        
        
        
        
        
        if($paid_amount!=0){
        
    
            
            
            
            

            
            
            $statement = $pdo->prepare("UPDATE `tbl_purchases` SET `paid`=paid+'$paid_amount' WHERE id=?");
            $result = $statement->execute(array($purchase_id)); 
                        
            
            
           if($result)
           {
               
               $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`, `discount`, `purchase_id`, `customer_id`, 
               `scheme_id`, `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`, `supplier_id`,
               `weight`, `per_gm_amount`) VALUES (?,?,?,?,?,?,
               ?,?,?,?,?,?,?,?,
               ?,?)");
               $result = $statement->execute(array($payment_date, $type, $paid_amount, $discount_amount, $purchase_id, $customer_id,
               $account_id, $accounts, $payment_type, $reference, $today_date, $session_id, $notes, $supplier_id,
               $metal_weight, $metal_rate)); 

                
              
               
                $pdo->commit();
                
                $return_arr['message']='Payment Added Successfully...';
                $return_arr['status']=200;
           } }
           else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
            
            
             
     }catch(PDOException $e){
         $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}



if(isset($_POST['type']) && $_POST['type']=='create_multiple_payments'){
    
     try{
         
        $pdo->beginTransaction(); 
        
        
        $sale_id = (isset($_POST['sale_id'])) ? $_POST['sale_id'] : "";
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        
        $type = "Credit";
        $accounts = 1;
        $discount_amount = $_POST['discount_amount'];
        
        $cash_amount = $_POST['cash_amount'];
        $upi_amount = $_POST['upi_amount'];
        $amount_type_3 = $_POST['payment_type_3'];
        $reference = $_POST['reference'];
        $notes = $_POST['notes'];
        
        $discount_passed_id = $_POST['discount_passed_id'];
        
        if($discount_amount=="" || $discount_amount=="0"){
            
        }else{
            $statement = $pdo->prepare("UPDATE `tbl_sales` SET `discount_amount`=discount_amount+'$discount_amount', `discount_passed_id`=? WHERE id=?");
            $result = $statement->execute(array($discount_passed_id, $sale_id)); 
        }
        
        
        if($cash_amount=="" || $cash_amount=="0"){
            
        }else{
            $payment_type = 1;
            $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`,  `sale_id`,  
                       `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`) VALUES (?,?,?,?,
                       ?,?,?,?,?,?)");
            $result = $statement->execute(array($payment_date, $type, $cash_amount,  $sale_id,
                       $accounts, $payment_type, $reference, $today_date, $session_id, $notes)); 
        }
        
        
        if($upi_amount=="" || $upi_amount=="0"){
            
        }else{
            $payment_type = 8;
            $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`,  `sale_id`,  
                       `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`) VALUES (?,?,?,?,
                       ?,?,?,?,?,?)");
            $result = $statement->execute(array($payment_date, $type, $upi_amount,  $sale_id,
                       $accounts, $payment_type, $reference, $today_date, $session_id, $notes)); 
        }
        
        if($amount_type_3=="" || $amount_type_3=="0"){
            
        }else{
            $payment_type = 7;
            $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`,  `sale_id`,  
                       `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`) VALUES (?,?,?,?,
                       ?,?,?,?,?,?)");
            $result = $statement->execute(array($payment_date, $type, $amount_type_3,  $sale_id,
                       $accounts, $payment_type, $reference, $today_date, $session_id, $notes)); 
        }
        
            
            
           if($result){
               
               
                // Payments - Here
                $statement = $pdo->prepare("SELECT SUM(amount) as total_paid_amount FROM tbl_payments e where e.sale_id=?");
                $statement->execute(array($sale_id));
                $emp_data = $statement->fetchAll(PDO::FETCH_ASSOC);
                $totalData = $statement->rowCount();
                if($totalData>0){
                    
                    $total_paid_amount = $emp_data[0]['total_paid_amount'];
                    $statement = $pdo->prepare("UPDATE `tbl_sales` SET `paid`=paid+'$total_paid_amount', `status`=1 WHERE id=?");
                    $result = $statement->execute(array($sale_id)); 
    
                }
                
                // Stock Minus - Here
                $statement_stocks = $pdo->prepare("SELECT * FROM `tbl_sale_items` e where e.sale_id=?");
                $statement_stocks->execute(array($sale_id));
                $sales_data = $statement_stocks->fetchAll(PDO::FETCH_ASSOC);
                $totalDatas = $statement_stocks->rowCount();
                if($totalData>0){
                    
                    foreach($sales_data as $sale){
                        $product_id = $sale['product_id'];
                        $quantity = $sale['quantity'];
                        $sale_items_id = $sale['id'];
                        $stock_minus_status = $sale['stock_minus_status'];
                        
                        
                        
                        if($stock_minus_status==1){
                            
                            
                        $statement_products = $pdo->prepare("SELECT * FROM `tbl_product_variants` e where e.id=?");
                        $statement_products->execute(array($product_id));
                        $products_datas = $statement_products->fetchAll(PDO::FETCH_ASSOC);
                        $products_totalDatas = $statement_products->rowCount();
                        
                        if($products_totalDatas>0){
                            if($products_datas[0]['sales_status']==1){
                                $statement_product = $pdo->prepare("UPDATE `tbl_sale_items` SET `stock_minus_status`=? WHERE id=?");
                                $product_result = $statement_product->execute(array(0, $sale_items_id)); 
                                
                                $statement_product = $pdo->prepare("UPDATE `tbl_product_variants` SET `sales_status`=?, `quantity`=quantity-? WHERE id=?");
                                $product_result = $statement_product->execute(array(0, $quantity, $product_id));
                            }else{
                                $pdo->rollBack();
                                $return_arr['status']=400;
                                $return_arr['error'] = true;
                                $return_arr['message'] = "This Product is Already Saled!";
                                print_r(json_encode($return_arr));
                                return false;
                                exit(); 
                            }
                        }
                
                             
                        
                        
                        
                        
                        }
                        
                        
                    }
                
    
                }
                
                
               
                $pdo->commit();
                
                $return_arr['message']='Payment Added Successfully...';
                $return_arr['status']=200;
           }else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
            
            
             
    }catch(PDOException $e){
        $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
    }   
    echo json_encode($return_arr);
}






/********************************** Update Payments Starts Here **********************************/
if(isset($_POST['type']) && $_POST['type']=='update_purchase_payment'){
    
     try{
         
        $pdo->beginTransaction(); 
        
        $payment_update_id = $_POST['payment_id'];
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        $amount = (isset($_POST['paid_amount'])) ? $_POST['paid_amount'] : "";
        $payment_type = (isset($_POST['payment_type'])) ? $_POST['payment_type'] : "";
        $reference = (isset($_POST['reference'])) ? $_POST['reference'] : "";
        $notes = (isset($_POST['notes'])) ? $_POST['notes'] : "";
        
        $this_payment = $_POST['this_payment'];
        $purchase_id = $_POST['purchase_id'];
        
        
        if($amount!=0){
            
            $statement = $pdo->prepare("UPDATE tbl_purchases SET paid=paid-'$this_payment' WHERE id=?");
            $result = $statement->execute(array($purchase_id));
            
            $statement = $pdo->prepare("UPDATE tbl_purchases SET paid=paid+'$amount' WHERE id=?");
            $result = $statement->execute(array($purchase_id));
    
    
     
            
            $statement = $pdo->prepare("UPDATE `tbl_payments` SET `date`=?, `amount`=?, `payment_type`=?, `reference_no`=?, `notes`=?, `updated_by`=?, `updated_at`=? WHERE id=?");
            $result = $statement->execute(array($payment_date, $amount, $payment_type, $reference, $notes, $session_id, $updated_at, $payment_update_id)); 
        
            
            
           if($result){
          
                $pdo->commit();
                $return_arr['message']='Payment Updated Successfully...';
                $return_arr['status']=200;
           } }
           else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
            
            
             
     }catch(PDOException $e){
         $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}


if(isset($_POST['type']) && $_POST['type']=='update_sales_payment'){
    
     try{
         
        $pdo->beginTransaction(); 
        
        $payment_update_id = $_POST['payment_id'];
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        $amount = (isset($_POST['paid_amount'])) ? $_POST['paid_amount'] : "";
        $payment_type = (isset($_POST['payment_type'])) ? $_POST['payment_type'] : "";
        $reference = (isset($_POST['reference'])) ? $_POST['reference'] : "";
        $notes = (isset($_POST['notes'])) ? $_POST['notes'] : "";
        
        $this_payment = $_POST['this_payment'];
        $sales_id = $_POST['sales_id'];
        
        
        if($amount!=0){
            
            $statement = $pdo->prepare("UPDATE tbl_sales SET paid=paid-'$this_payment' WHERE id=?");
            $result = $statement->execute(array($sales_id));
            
            $statement = $pdo->prepare("UPDATE tbl_sales SET paid=paid+'$amount' WHERE id=?");
            $result = $statement->execute(array($sales_id));
    
    
     
            
            $statement = $pdo->prepare("UPDATE `tbl_payments` SET `date`=?, `amount`=?, `payment_type`=?, `reference_no`=?, `notes`=?, `updated_by`=?, `updated_at`=? WHERE id=?");
            $result = $statement->execute(array($payment_date, $amount, $payment_type, $reference, $notes, $session_id, $updated_at, $payment_update_id)); 
        
            
            
           if($result){
          
                $pdo->commit();
                $return_arr['message']='Payment Updated Successfully...';
                $return_arr['status']=200;
           } }
           else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
            
            
             
     }catch(PDOException $e){
         $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
        }   
    echo json_encode($return_arr);
}

/********************************** Update Payments Enddss Here **********************************/


if(isset($_POST['field_type']) && $_POST['field_type']=='add_advance_payment'){
    
    
    try{
         
        $pdo->beginTransaction(); 
        
        $advance_id = (isset($_POST['advance_id'])) ? $_POST['advance_id'] : "";
        $total_amount = (isset($_POST['total_amount'])) ? $_POST['total_amount'] : "";
        
        
        $paid_amount = (isset($_POST['paid_amount'])) ? $_POST['paid_amount'] : "";
        $payment_type = (isset($_POST['payment_type'])) ? $_POST['payment_type'] : "";
        $reference = (isset($_POST['reference'])) ? $_POST['reference'] : "";
        $notes = (isset($_POST['notes'])) ? $_POST['notes'] : "";
        $payment_date = (isset($_POST['payment_date'])) ? $_POST['payment_date'] : "";
        
        
        $db_advance = (isset($_POST['db_advance'])) ? $_POST['db_advance'] : "";
        
        $type = "Credit";
        $accounts = 4;
        $today_date = date('Y-m-d');
        $balance = $total_amount-$db_advance;
        
        $advance_get_data = $pdo->prepare("SELECT * FROM tbl_advance_voucher WHERE id=?");
        $advance_get_data->execute(array($advance_id));
        $advance_data = $advance_get_data->fetchAll(PDO::FETCH_ASSOC);
        $totalData = $advance_get_data->rowCount();
        $customer_id = '';
        if($totalData==1){
            $customer_id = $advance_data[0]['customer_id'];
        }
        
        if($paid_amount!=0){
        
            
            $statement = $pdo->prepare("UPDATE `tbl_advance_voucher` SET `paid`=?, `advance_amount`=?, WHERE id=?");
            $result = $statement->execute(array($paid_amount, $paid_amount, $advance_id)); 
                        
             
            $statement = $pdo->prepare("INSERT INTO `tbl_payments` (`date`, `type`, `amount`, `advance_id`, `customer_id`, 
                            `accounts`, `payment_type`, `reference_no`, `created_date`, `created_by`, `notes`) VALUES (?,?,?,?,?,
                            ?,?,?,?,?,?)");
            $result = $statement->execute(array($payment_date, $payment_type, $paid_amount, $advance_id,  $customer_id,
                            $accounts, $payment_type, $reference, $today_date, $session_id, $notes)); 
                        
            
            
            if($result){
                $pdo->commit();
                $return_arr['message']='Advance Voucher Payment Added Successfully...';
                $return_arr['status']=200;
            }else{
                $return_arr['message']='Something Went Wrong..';
                $return_arr['status']=400;
            }
        }
        
        
    
    
    }catch(PDOException $e){
         $pdo->rollBack();
        $return_arr['message']="$e";
        $return_arr['status']=500;
    }   
    
    echo json_encode($return_arr);

    
}



?>