<?php

include_once("connect.php");
include_once("session.php");

$data = json_decode($_POST['data']);
$invoices = $data->Invoice;
$credits = $data->Credits;
$summary = $data->Summary;
$payment = $data->PaymentInformation;
$payment->CPD = $payment->CPD?1:0;
$customer = new Customer($summary->AccountNumber);

$payment->CPDDate = $payment->CPDDate==NULL?"0000-00-00 00:00:00":$payment->CPDDate;
$query = "INSERT INTO PAYMENT_HEAD (PaymentDate, AccountNumber, SalesmanID, CPD, CPDDate, CashAmount, CheckAmount, `Notes`, `CollectingUser`) VALUES (DATE_ADD(NOW(), INTERVAL -4 HOUR), '" . $summary->AccountNumber . "', '" . $customer->Salesman->ID . "', " . $payment->CPD . " , '" . $payment->CPDDate . "', " . $payment->Cash . ", " . $payment->Check . ", '" . $data->Notes . "', '" . $_SESSION['SalesmanID'] . "')";
$result = mysqli_query($con, $query);
$paymentID = mysqli_insert_id($con);
foreach($invoices as $invoice){
    $partialPayment = ($invoice->Total != $invoice->PartialPayment)?1:0;
    $query = "INSERT INTO PAYMENT_DETAIL (PaymentID, InvoiceID, InvoiceDate, Reference, PartialPayment, SubtotalAmount, DiscountAmount, TaxAmount, PaymentAmount) VALUES ($paymentID, '" . mysqli_real_escape_string($con,$invoice->InvoiceID) . "', '" . $invoice->InvoiceDate . "', '" . mysqli_real_escape_string($con, $invoice->Remarks) . "', $partialPayment, " . $invoice->Subtotal . ", " . $invoice->Discount . ", " . $invoice->Tax . ", " . $invoice->PartialPayment . ");";
    if(mysqli_query($con, $query)){
        
    }else{
        die(mysqli_error($con) . "<br />" . $query);
    }
}

foreach($payment->CheckDetail as $check){
    
    $query = "INSERT INTO PAYMENT_CHECK (PaymentID, CheckNumber, Amount) VALUES ($paymentID, '" . $check->Number . "', " . $check->Amount . ")";
    if(mysqli_query($con, $query)){
        
    }else{
        die(mysqli_error($con) . "<br />" . $query);
    }
}
include_once("./modules/payment/payment.classes.php");
$obj = new Payment($paymentID);
$obj->SendPaymentEmail();
echo $paymentID;



?>