<?php
require "global.ajax.php";

switch ($_GET["op"]) {

    case 'ajaxSaveUpdate':

        // POST VARIABLES
        $inv_id = isset($_POST["inv_id"]) ? funCheckInput($_POST["inv_id"]) : "";
        $inv_ent_id = isset($_POST["inv_ent_id"]) ? funCheckInput($_POST["inv_ent_id"]) : "";
        $inv_date = isset($_POST["inv_date"]) ? funCheckInput($_POST["inv_date"]) : "";
        $inv_due_date = isset($_POST["inv_due_date"]) ? funCheckInput($_POST["inv_due_date"]) : "";
        $inv_amount = isset($_POST["inv_amount"]) ? funCheckInput($_POST["inv_amount"]) : "";
        $inv_discount_percent = isset($_POST["inv_discount_percent"]) ? funCheckInput($_POST["inv_discount_percent"]) : "";
        $inv_discount_amount = isset($_POST["inv_discount_amount"]) ? funCheckInput($_POST["inv_discount_amount"]) : "";
        $inv_subtotal = isset($_POST["inv_subtotal"]) ? funCheckInput($_POST["inv_subtotal"]) : "";
        $inv_tax_percent = isset($_POST["inv_tax_percent"]) ? funCheckInput($_POST["inv_tax_percent"]) : "";
        $inv_tax_amount = isset($_POST["inv_tax_amount"]) ? funCheckInput($_POST["inv_tax_amount"]) : "";
        $inv_total_amount = isset($_POST["inv_total_amount"]) ? funCheckInput($_POST["inv_total_amount"]) : "";
        $inv_debt = isset($_POST["inv_debt"]) ? funCheckInput($_POST["inv_debt"]) : "";
        $inv_note = isset($_POST["inv_note"]) ? funCheckInput($_POST["inv_note"]) : "";
        $inv_terms = isset($_POST["inv_terms"]) ? funCheckInput($_POST["inv_terms"]) : "";

        $saveOrUpdate = "Saved";

        $isNew = empty(trim($inv_id));

        if ($isNew) {

            $inv_code = "INV{$inv_id}-" . createTokenNumber('tb_invoices', 'inv_code', '8') . "-{$inv_ent_id}";

            $sql = "INSERT INTO tb_invoices (
            inv_ent_id
            inv_code
            inv_date
            inv_due_date
            inv_amount
            inv_discount_percent
            inv_discount_amount
            inv_subtotal
            inv_tax_percent
            inv_tax_amount
            inv_total_amount
            inv_debt
            inv_note
            inv_terms
            inv_created_by) VALUES (
            '$inv_ent_id'
            ,'$inv_code'
            ,'$inv_date'
            ,'$inv_due_date'
            ,'$inv_amount'
            ,'$inv_discount_percent'
            ,'$inv_discount_amount'
            ,'$inv_subtotal'
            ,'$inv_tax_percent'
            ,'$inv_tax_amount'
            ,'$inv_total_amount'
            ,'$inv_debt'
            ,'$inv_note'
            ,'$inv_terms'
            ,'$session_user_id');";
            // exit($sql);

            $answer = executeQueryPDOReturnLastId($sql, $saveOrUpdate, "SAVE INVOICES");

            if ($answer["status"] == "success") {
                $inv_id = $answer["id"];
            } else {
                $response = array("status" => "error", "message" => "Error <br> {$answer['message']}");
                echo json_encode($response);
                exit();
            }
        } else {

            $saveOrUpdate = "Updated";

            $sql = "UPDATE tb_invoices SET
            inv_date = '$inv_date'
            ,inv_due_date = '$inv_due_date'
            ,inv_amount = '$inv_amount'
            ,inv_discount_percent = '$inv_discount_percent'
            ,inv_discount_amount = '$inv_discount_amount'
            ,inv_subtotal = '$inv_subtotal'
            ,inv_tax_percent = '$inv_tax_percent'
            ,inv_tax_amount = '$inv_tax_amount'
            ,inv_total_amount = '$inv_total_amount'
            ,inv_debt = '$inv_debt'
            ,inv_note = '$inv_note'
            ,inv_terms = '$inv_terms'
            ,inv_updated_by = '$session_user_id'
			WHERE inv_id='$inv_id'";
            // exit($sql);

            $answer = executeQueryPDOApi($sql, $saveOrUpdate, "UPDATE_INVOICES");
        }

        /*=============================================
		SAVE PURCHASE DETAILS
		=============================================*/
        $sqlInvoicesDetails = "";

        if (isset($_POST["inv_item_description"]) && !empty($_POST["inv_item_description"])) {

            for ($row = 0; $row < count($_POST['inv_item_description']); $row++) {

                if (isset($_POST["inv_item_description"][$row])) {

                    $inv_item_inv_id = $inv_id;
                    $inv_item_ent_id = $inv_ent_id;
                    $inv_item_inv_code = $inv_code;
                    $inv_item_description = funCheckInput($_POST['inv_item_description'][$row]);
                    $inv_item_quantity = funCheckInput($_POST['inv_item_quantity'][$row]);
                    $inv_item_unit_price = funCheckInput($_POST['inv_item_unit_price'][$row]);
                    $inv_item_total = funCheckInput($_POST['inv_item_total'][$row]);

                    // IF EXISTE MORE DATA TO SAVE ADD A COMA FOR THE SECOND LINE
                    if (!empty(trim((string) $sqlInvoicesDetails))) {
                        $sqlInvoicesDetails .= ", ";
                    }

                    $sqlInvoicesDetails .= "('{$inv_item_inv_id}','{$inv_item_ent_id}','{$inv_item_inv_code}','{$inv_item_description}','{$inv_item_quantity}','{$inv_item_unit_price}','{$inv_item_total}')";
                }
            }
            // exit($sqlInvoicesDetails);

            // DELETE ALL PURCHASE DETAILS TO INSERT NEW ONES
            $sqlDeleteInvoicesDetails = "DELETE FROM tb_invoices_items WHERE inv_item_inv_id={$inv_id}";
            // exit($sqlDeleteInvoicesDetails);
            executeQueryPDO($sqlDeleteInvoicesDetails);

            $sqlInsertInvoicesDetails = "INSERT INTO tb_invoices_items (inv_item_inv_id,inv_item_ent_id,inv_item_inv_code,inv_item_description,inv_item_quantity,inv_item_unit_price,inv_item_total) VALUES {$sqlInvoicesDetails}";

            // exit($sqlInsertInvoicesDetails);
            $answer = executeQueryPDOApi($sqlInsertInvoicesDetails, $saveOrUpdate, "DETAILS INVOICES");
        }

        /*=============================================
		SAVE SALE PAYMENT DETAILS
		=============================================*/
        $sqlInvoicesPaymentsDetails = "";

        if (isset($_POST["pay_inv_method"]) && !empty($_POST["pay_inv_method"])) {

            for ($row = 0; $row < count($_POST['pay_inv_method']); $row++) {

                if (isset($_POST["pay_inv_method"][$row])) {

                    $pay_inv_id = $inv_id;
                    $pay_inv_ent_id = $inv_ent_id;
                    $pay_inv_code = $inv_code;
                    $pay_inv_date = $inv_date;
                    $pay_inv_method = funCheckInput($_POST['pay_inv_method'][$row]);
                    $pay_inv_amount = funCheckInput($_POST['pay_inv_amount'][$row]);
                    $pay_inv_note = funCheckInput($_POST['pay_inv_note'][$row]);
                    $pay_inv_created_by = $session_user_id;

                    // IF EXISTE MORE DATA TO SAVE ADD A COMA FOR THE SECOND LINE
                    if (!empty(trim((string) $sqlInvoicesPaymentsDetails))) {
                        $sqlInvoicesPaymentsDetails .= ", ";
                    }

                    $sqlInvoicesPaymentsDetails .= "('{$pay_inv_id}','{$pay_inv_ent_id}','{$pay_inv_code}','{$pay_inv_date}','{$pay_inv_method}','{$pay_inv_amount}','{$pay_inv_note}','{$pay_inv_created_by}')";
                }
            }
            // exit($sqlInvoicesPaymentsDetails);

            // DELETE ALL PURCHASE DETAILS TO INSERT NEW ONES
            $sqlDeleteInvoicesPaymentsDetails = "DELETE FROM tb_invoices_payments WHERE pay_inv_id={$inv_id}";
            // exit($sqlDeleteInvoicesPaymentsDetails);
            executeQueryPDO($sqlDeleteInvoicesPaymentsDetails);

            $sqlInsertInvoicesPaymentsDetails = "INSERT INTO tb_invoices_payments (pay_inv_id,pay_inv_ent_id,pay_inv_code,pay_inv_date,pay_inv_method,pay_inv_amount,pay_inv_note,pay_inv_created_by) VALUES {$sqlInvoicesPaymentsDetails}";

            // exit($sqlInsertInvoicesPaymentsDetails);
            $answer = executeQueryPDOApi($sqlInsertInvoicesPaymentsDetails, $saveOrUpdate, "DETAILS INVOICES");
        }

        // RETURN MESSAGE ALERT
        if ($answer['status'] == "success") {
            $response = array("message" => $translate['saved_successfully'], "status" => "success");
            if ($answer['type'] == "Updated") $response = array("message" => $translate['updated_successfully'], "status" => "success");
        } elseif ($answer['status'] == "error") {
            $response = array("message" => "{$translate['execution_failed']} <br> {$answer['message']}", "status" => "error");
            if ($answer['type'] == "Updated") $response = array("message" => "{$translate['execution_failed']}  <br> {$answer['message']}", "status" => "error");
        } else {
            $response = array("message" => "Error <br> {$answer['message']}", "status" => "error");
        }

        echo json_encode($response);

        break;


    case 'ajaxInvoicesList':

        $ent_id = isset($_GET["ent_id"]) ? funCheckInput($_GET["ent_id"]) : "";
        $fromDate = isset($_GET["fromDate"]) ? funCheckInput($_GET["fromDate"]) : "";
        $toDate = isset($_GET["toDate"]) ? funCheckInput($_GET["toDate"]) : "";
        $status = isset($_GET["status"]) ? funCheckInput($_GET["status"]) : "";

        $whereDate = "WHERE DATE_FORMAT(inv_date, '%Y-%m-%d') BETWEEN '{$last7Days}' AND '{$todayDate}'";
        if (!empty($toDate)) $whereDate = "WHERE DATE_FORMAT(inv_date, '%Y-%m-%d') BETWEEN '{$fromDate}' AND '{$toDate}'";

        $whereEntId = "";
        if (!empty($ent_id) && $ent_id != "All") $whereEntId = "AND inv_ent_id = '{$ent_id}'";

        $whereStatus = "";
        if (!empty($ent_id) && $status != "All") $whereStatus = "AND inv_status = '{$status}'";

        $sql = "SELECT
        inv_id
        ,inv_ent_id
		,(select ent_name FROM tb_enterprises WHERE ent_id = inv_ent_id) AS enterprise_name
        ,inv_code
		,DATE_FORMAT(inv_date, '%Y-%m-%d') AS inv_date
		,DATE_FORMAT(inv_due_date, '%Y-%m-%d') AS inv_due_date
        ,inv_subtotal
        ,inv_discount_percent
        ,inv_discount_amount
        ,inv_amount
        ,inv_tax_percent
        ,inv_tax_amount
        ,inv_total_amount
        ,inv_debt
        ,inv_note
        ,inv_terms
        ,inv_status
		,(select CONCAT(user_firstname,' ',user_lastname) FROM tb_users WHERE user_id = inv_created_by) AS createdBy
		FROM tb_invoices
        $whereDate $whereEntId $whereStatus
		GROUP BY inv_id ORDER BY inv_id DESC;";

        // exit($sql);

        $result = executePDOFetchAllAPI($sql);
        echo json_encode($result);

        break;


    case 'ajaxShowInvoicesDetails':
        $inv_id = isset($_GET["inv_id"]) ? funCheckInput($_GET["inv_id"]) : "";

        if (!empty(trim((string) $inv_id))) {
            $sqlGetExpenseDetails = "SELECT
            inv_item_description
            ,inv_item_quantity
            ,inv_item_unit_price
            ,inv_item_total
            FROM tb_invoices_items WHERE inv_item_inv_id = '{$inv_id}'";
            $resGetExpenseDetails = executePDOFetchAllAPI($sqlGetExpenseDetails);
            echo json_encode($resGetExpenseDetails);
        } else {
            echo json_encode(array('status' => 'error', 'message' => 'Empty ID value was sent'));
        }
        break;


    case 'ajaxCancelData':

        $transaction_id = isset($_POST["transaction_id"]) ? funCheckInput($_POST["transaction_id"]) : "";
        $transaction_reason = isset($_POST["transaction_reason"]) ? funCheckInput($_POST["transaction_reason"]) : "";

        $sqlInvoiceInfo = "SELECT
		inv_id
		,inv_ent_id
		,IFNULL(inv_total_amount,0) AS inv_total_amount
		FROM tb_invoices
		WHERE inv_id = {$transaction_id};";
        $invInfo = executePDOFetchOne($sqlInvoiceInfo);

        $sql = "UPDATE tb_invoices SET inv_status = 'Disabled' WHERE inv_id ='{$transaction_id}';
		UPDATE tb_invoices_payments SET pay_inv_status = 'Disabled' WHERE pay_inv_id ='{$transaction_id}';";
        $result = executeQueryPDO($sql, 'success', 'error');

        if ($result['status'] == "success") {

            $inv_total_amount = number_format($invInfo['inv_total_amount'], 2);

            $log_description = "{$session_user_fullname} (ID:{$session_user_id}), Cancelled an invoice (ID:{$invInfo['inv_id']}), for a total of $'{$inv_total_amount}' the reason given is: {$transaction_reason}.";

            fnGenerateNewCancelPassword($session_user_ent_id);

            $saveLogs = saveLog($invInfo['inv_ent_id'], $session_user_pos_id, $session_user_id, $log_description, $currentDateTimeByZone);
            // sendEmail($emailSender,$emailSenderName,$emailSubject,$emailReciver,$emailReciverName,$log_description);
            $response = array('title' => "Canceled successfully", 'message' => "This action has been registered in the audit system for control purposes", 'type' => 'success');
        } else {
            $response = array('message' => $translate['execution_failed'], 'type' => 'error');
        }
        echo json_encode($response);

        break;
}
