<?php 
include 'session.php';
// echo 'hi';
extract($_REQUEST);
$act=$action;
// echo $overall_bill_id = implode(",",$overall_bill_id);
// 		exit;
$payment_date = date('Y-m-d', strtotime($_POST['payment_date']));

switch($act)
{
	case 'insert':	
        $overall_bill_id = implode(",",$overall_bill_id);
        $overall_bill_amt = implode(",",$overall_bill_amt);
        $overall_bill_date = implode(",",$overall_bill_date);
        $overall_bill_company = implode(",",$overall_bill_company);
        $overall_bill_fin_year = implode(",",$overall_bill_fin_year);
        $overall_bill_totalamt = implode(",",$overall_bill_totalamt);
        $overall_bill_aftDiscount = implode(",",$overall_bill_aftDiscount);
        $overall_bill_gst = implode(",",$overall_bill_gst);
        $overall_bill_finalamt = implode(",",$overall_bill_finalamt);
        $overall_bill_returnamt = implode(",",$overall_bill_returnamt);



        $str_payment_main = "INSERT INTO `t_payment_main`( `payment_date`, `company_id`, `cus_id`, `bill_amount`, `received_amount`, `less_amount`, `notes`, `payment_type`,`payment_status`, `ref_no`, `IsActive`, `UserId`, `createddate`) 
        VALUES ('".$payment_date."','".$sel_company."', '".$sel_customer."', '".$bill_amount."', '".$received_amount."', '".$less_amount."', '".$notes."', '".$payment_type."','".$payment_status."', '".$ref_no."', '1', '".$_SESSION["UserId"]."', NOW() ) ";
// echo $str_payment_main;
// echo $new = $_SESSION["Financial_id"];
// echo 'hi';
// exit;
// $particulars = ;
$rslt = $db->insert($str_payment_main);	

$Last_insert_id=$db->insert_id;
// echo $overall_bill_id;
// exit;

if($less_amount <= 0){
    // echo 'hi';
    // exit;

$transaction_details = "INSERT INTO `transaction_details`( `date`, `bill_no`, `particulars`, `debit`, `financial_id`, `company_id`, `cus_id`, `payment_type`,`ref_no`, `createddate`, `modifieddate`, `UserId`, `IsActive`)
    VALUES  ('".$payment_date."', '".$overall_bill_id."', 'Payment Received','".$received_amount."','".$_SESSION["Financial_id"]."', '".$sel_company."', '".$sel_customer."', '".$payment_type."', '".$ref_no."', NOW(), NOW(), '".$_SESSION["UserId"]."', '1'  ) ";
// echo $transaction_details;
 $rslt = $db->insert($transaction_details);	
}

else if ($less_amount > 0)
{
    $transaction_details = "INSERT INTO `transaction_details`( `date`, `bill_no`, `particulars`, `debit`, `financial_id`, `company_id`, `cus_id`, `payment_type`,`ref_no`, `createddate`, `modifieddate`, `UserId`, `IsActive`)
    VALUES  ('".$payment_date."', '".$overall_bill_id."', 'Payment Received','".$received_amount."','".$_SESSION["Financial_id"]."', '".$sel_company."', '".$sel_customer."', '".$payment_type."', '".$ref_no."', NOW(), NOW(), '".$_SESSION["UserId"]."', '1'  ) ";

    $transaction_less = "INSERT INTO `transaction_details`( `date`, `bill_no`, `particulars`, `debit`, `financial_id`, `company_id`, `cus_id`,  `createddate`, `modifieddate`, `UserId`, `IsActive`)   
    VALUES  ('".$payment_date."', '".$overall_bill_id."', 'Commision / Less ','".$less_amount."','".$_SESSION["Financial_id"]."', '".$sel_company."', '".$sel_customer."',  NOW(), NOW(), '".$_SESSION["UserId"]."', '1'  ) ";
// echo $transaction_details;
// echo $transaction_less;
//  exit;
$rslt = $db->insert($transaction_details);	
$rslt = $db->insert($transaction_less);	

}
// exit;
      $balance = " SELECT * FROM total_balance where financial_id = '".$_SESSION["Financial_id"]."' AND company_id = '".$sel_company."' AND cus_id = '".$sel_customer."' ";

$balance_result = $db->get_row($balance);
if ($balance_result) 
{
	$newDebitAmount = (float)$received_amount;

	$balance_update = "UPDATE total_balance SET debit = debit + '".$newDebitAmount."', modifieddate = NOW(),  UserId = '".$_SESSION["UserId"]."'  WHERE financial_id = '".$_SESSION["Financial_id"]."' AND company_id = '".$sel_company."' AND cus_id = '".$sel_customer."' ";

}
else {
	$newDebitAmount = (float)$received_amount;

	$balance_update = "INSERT INTO total_balance(financial_id, company_id, cus_id, credit, debit, createddate, modifieddate, IsActive, UserId  ) VALUES ('".$_SESSION["Financial_id"]."', '".$sel_company."', '".$sel_customer."', '0.00','".$newDebitAmount."', NOW(), NOW(), '1', '".$_SESSION["UserId"]."'   ) ";
}
$rslt = $db->insert($balance_update);



        if (isset($Last_insert_id) && !empty($Last_insert_id)) {

            $bill_ids_array = explode(",", $overall_bill_id);   
            $bill_amt_array = explode(",", $overall_bill_amt);
            $bill_date_array = explode(",", $overall_bill_date);
            $bill_company_array = explode(",", $overall_bill_company);
            $bill_fin_year_array = explode(",", $overall_bill_fin_year);
            $bill_totalamt_array = explode(",", $overall_bill_totalamt);
            $bill_aftDiscount_array = explode(",", $overall_bill_aftDiscount);
            $bill_gst_array = explode(",", $overall_bill_gst);
            $bill_finalamt_array = explode(",", $overall_bill_finalamt);
            $bill_returnamt_array = explode(",", $overall_bill_returnamt);

            $pdt_cnt = count($bill_ids_array);
                //   120=          100                     20
            $balance_amt = $received_amount + $less_amount;

            for ($i = 0; $i < $pdt_cnt; $i++) {
                $current_bill_id = $bill_ids_array[$i]; 
				$current_bill_date = $bill_date_array[$i]; 
				$current_bill_amt = $bill_amt_array[$i]; 
                $current_bill_company = $bill_company_array[$i];
                $current_bill_fin_year = $bill_fin_year_array[$i];
                $current_bill_totalamt = $bill_totalamt_array[$i];
                $current_bill_aftDiscount = $bill_aftDiscount_array[$i];
                $current_bill_gst = $bill_gst_array[$i];
                $current_bill_finalamt = $bill_finalamt_array[$i];
                $current_bill_returnamt = $bill_returnamt_array[$i];
                $current_bill_date = date('Y-m-d', strtotime($current_bill_date));
                                    // 120 - 30
                $single_bill_amt =  $balance_amt - $current_bill_amt ;
                $balance_amt = $single_bill_amt;
// echo $current_bill_amt;
//             echo    $paid_amt = $current_bill_amt - $single_bill_amt;
            // exit;

        if($payment_status == '2')
        {
            $str_insert_det=" INSERT INTO `t_payment_details`( `payment_id`, `s_bill_no`, `s_bill_date`, `company`, `financial`, `total_amount`, `after_discount`, `gst_amt`, `bill_amount`, `return_amount`,`paid_amt`, `final_amount`, `IsActive`, `UserId`, `createddate`)
             VALUES ('".$Last_insert_id."','".$current_bill_id."','".$current_bill_date."','".$current_bill_company."', '".$current_bill_fin_year."', '".$current_bill_totalamt."', '".$current_bill_aftDiscount."', '".$current_bill_gst."', '".$current_bill_finalamt."', '".$current_bill_returnamt."', '".$current_bill_amt."','".$received_amount."', '1', '".$_SESSION["UserId"]."', NOW() )";

            $bill_status = "UPDATE transaction_details SET payment_status = '".$payment_status."'  WHERE bill_no = '".$current_bill_id."'  AND particulars = 'Sales' AND `financial_id`= (
                SELECT financial_id FROM m_financial_year WHERE CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) = '".$current_bill_fin_year."' ) AND company_id = '" . $sel_company . "' AND cus_id = '".$sel_customer. "'  ";

            $pay_status = "UPDATE t_sales_payment SET payment_status_id = '".$payment_status."'  WHERE s_bill_no = (
                SELECT s_bill_no FROM  t_sales_entry_main WHERE actu_bill_no = '".$current_bill_id."' AND financial_id = (
                    SELECT financial_id FROM m_financial_year WHERE CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) = '".$current_bill_fin_year."' )AND company_id = '" . $sel_company . "' AND cus_id = '".$sel_customer. "' ) ";
// echo $bill_status;
// exit;
            $db->insert($pay_status);
            $db->insert($str_insert_det);
            $db->insert($bill_status);
        }
        else  if($payment_status == '1')
        {
            $str_insert_det=" INSERT INTO `t_payment_details`( `payment_id`, `s_bill_no`, `s_bill_date`, `company`, `financial`, `total_amount`, `after_discount`, `gst_amt`, `bill_amount`, `return_amount`,`paid_amt`, `final_amount`, `IsActive`, `UserId`, `createddate`)
             VALUES ('".$Last_insert_id."','".$current_bill_id."','".$current_bill_date."','".$current_bill_company."', '".$current_bill_fin_year."', '".$current_bill_totalamt."', '".$current_bill_aftDiscount."', '".$current_bill_gst."', '".$current_bill_finalamt."', '".$current_bill_returnamt."', '".$received_amount."', '0', '1', '".$_SESSION["UserId"]."', NOW() )";

            $pay_status = "UPDATE t_sales_payment SET payment_status_id = '".$payment_status."'  WHERE s_bill_no = (
                SELECT s_bill_no FROM  t_sales_entry_main WHERE actu_bill_no = '".$current_bill_id."' AND financial_id = (
                    SELECT financial_id FROM m_financial_year WHERE CONCAT(YEAR(f_start_date), ' - ', YEAR(f_end_date)) = '".$current_bill_fin_year."' )AND company_id = '" . $sel_company . "' AND cus_id = '".$sel_customer. "' ) ";
// echo $str_insert_det;
// exit;
            $db->insert($pay_status);
            $db->insert($str_insert_det);
        }
// exit;

    }

}

echo json_encode(array("rslt"=>"1")); //success
	
	break;

    case 'del':
        $edit_id = base64_decode($Id);
			// echo $edit_id;
            // exit;
        $query = "SELECT * FROM t_payment_details WHERE payment_id = $edit_id";
        $result = $db->get_rsltset($query);

        $bill_no = "SELECT * FROM t_payment_details WHERE payment_id = $edit_id";
		$bill_no_result = $db->get_rsltset($bill_no);
		$s_bill_no = $bill_no_result[0]['s_bill_no'];
		$s_bill_date = $bill_no_result[0]['s_bill_date'];
		
        $bill_ids_array = array();

        foreach ($result as $row) {


            $current_bill_id = $row['s_bill_no'];
            $current_bill_date = $row['s_bill_date'];
            
            $bill_payment = "SELECT s_bill_no FROM t_sales_entry_main WHERE actu_bill_no = '$current_bill_id' AND s_bill_date = '$current_bill_date' ";
            $bill_number = $db->get_rsltset($bill_payment);
            
            $s_bill_no = $bill_number[0]['s_bill_no'];

    //    echo $bill_payment;
    //    echo $s_bill_no;
    //    exit;
            // Output the update query for each iteration
            $query4 = "UPDATE t_sales_payment SET payment_status_id = '1' WHERE s_bill_no = '$s_bill_no'";
            $db->insert($query4);
    
            $bill_ids_array[] = $current_bill_id;
           
        }
        $s_bill_no_string = implode(',', $bill_ids_array);


        $query1 = "DELETE FROM t_payment_main WHERE id = $edit_id";
        $query2 = "DELETE FROM t_payment_details WHERE payment_id = $edit_id";
        $query3 = "DELETE FROM transaction_details WHERE bill_no = '".$s_bill_no_string."' AND particulars != 'Sales' AND particulars != ' Return' ";
        $query5 = "UPDATE transaction_details SET payment_status = null WHERE bill_no = '".$s_bill_no_string."' AND particulars = 'Sales' ";
        $db->query($query5);
        // exit;

    
    if ($db->insert($query1) && $db->insert($query2) && $db->insert($query3)  ) {
        echo json_encode(array("rslt" => "5", "msg" => "Payment Details Deleted Successfully"));
    } else {
        echo json_encode(array("rslt" => "-1", "err_msg" => "Error: " . $e->getMessage()));
    }
        break;

       

case 'update':
// echo    $edit_id = base64_decode($Id);
    // echo 'hi';
    // echo $edit_id;
    $str_update_main = " UPDATE `t_payment_main` SET `payment_type`= '".$payment_type."',`payment_status` = '".$payment_status."', `payment_date` = '".$payment_date."', `received_amount` = '".$received_amount."', `less_amount` = '".$less_amount."', `ref_no` = '".$ref_no."', `notes` = '".$notes."', `modifieddate`=NOW()  WHERE id = '".$edit_id."' ";
//  exit;

    if($payment_status == '2'){
        $str_update_details = "UPDATE `t_payment_details` SET paid_amt = '".$bill_amount."'  WHERE payment_id = '".$edit_id."' ";

    }
    else  if($payment_status == '1'){
        $str_update_details = "UPDATE `t_payment_details` SET paid_amt = '".$received_amount."'  WHERE payment_id = '".$edit_id."' ";

    }

    $rslt = $db->insert($str_update_main);	
    $rslt = $db->insert($str_update_details);	

 $query = "SELECT s_bill_no FROM t_payment_details WHERE payment_id = $edit_id";

$result = $db->get_rsltset($query);
// exit;
$bill_no = "SELECT s_bill_no FROM t_payment_details WHERE payment_id = $edit_id";
$bill_no_result = $db->get_rsltset($bill_no);
$s_bill_no = $bill_no_result[0]['s_bill_no'];

$bill_ids_array = array();

foreach ($result as $row) {


    $current_bill_id = $row['s_bill_no'];
    
    // Output the update query for each iteration
    $query4 = "UPDATE t_sales_payment SET payment_status_id = '1' WHERE s_bill_no = '$current_bill_id'";
    $db->insert($query4);

    $bill_ids_array[] = $current_bill_id;
   
}
$s_bill_no_string = implode(',', $bill_ids_array);
//  $received_amount;

  $transaction_details_upt = " UPDATE `transaction_details` SET `debit` = '".$received_amount."',ref_no = '".$ref_no."', payment_type = '".$payment_type."', date = '".$payment_date."'  WHERE bill_no = '".$s_bill_no_string."'  AND  particulars = 'Payment Received' ";

 $transaction_details_less_upt = " UPDATE `transaction_details` SET `debit` = '".$less_amount."', date = '".$payment_date."'  WHERE bill_no = '".$s_bill_no_string."'  AND  particulars = 'Commision / Less' ";
//  exit;

    $db->insert($transaction_details_upt) ;
    $db->insert($transaction_details_less_upt)  ;

    echo json_encode(array("rslt"=>"2")); //update success

    break;
    }
    