<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();

if (!isset($_SESSION["user_id"])) {
    header("location:../../logout.php");
    exit();
}

require_once "../magic/DataBase.php";
$dataBase = new DataBase();
$conn = $dataBase->getConnection();

$branch      = $_SESSION["branch"];
$father      = $_SESSION["user_id"];
$sanad_date  = date("Y-m-d");

$data  = [];
$error = [];

if (!empty($_POST['id3'])) {

    $contract_id   = $_POST['id3'];
    $money_out     = $_POST['money_out'];
    $comm          = $_POST['comm3'];
    $payOutMethod  = $_POST['payOutMethod'];
    $iban          = $_POST['iban'];

    require_once "../op/close_up.php";

    $Number = '/^[0-9]+(\.[0-9]{1,2})?$/';

    /* ------------------------ VALIDATION ------------------------ */

    if (empty($money_out)) {
        $error["money_out"] = "من فضلك سجل المبلغ ليتم حفظ السند";
    }

    if (!preg_match($Number, $money_out)) {
        $error["money_out"] = "من فضلك تأكد من رقم المبلغ";
    }

    // PayOutMethod is NOT numeric
    if (empty($payOutMethod)) {
        $error["payOutMethod"] = "من فضلك اختر طريقة الدفع";
    }

    $comm = !empty($comm) ? htmlspecialchars(strip_tags($comm)) : null;
    $iban = !empty($iban) ? htmlspecialchars(strip_tags($iban)) : null;

    /* ------------------------ CONTRACT CHECK ------------------------ */

    $contSQL = $conn->prepare("
        SELECT date_in, wanted, km_in, cont_status
        FROM contracts 
        WHERE contract_id = ?
    ");
    $contSQL->execute([$contract_id]);

    if ($contSQL->rowCount() === 0) {
        $data["msg"] = "<div class='alert alert-danger'><b>العقد غير موجود!</b></div>";
        echo json_encode($data);
        exit();
    }

    $boo         = $contSQL->fetch(PDO::FETCH_ASSOC);
    $date_in     = $boo['date_in'];
    $wanted      = $boo['wanted'];
    $km_in       = $boo['km_in'];
    $contstatus  = $boo['cont_status'];

    if (($wanted > 0) || ($sanad_date < $date_in)||($contstatus < 2)) {
        $data["msg"] = "<div class='alert alert-danger'>
            <b>... خطأ - مازال العقد ساري أو اغلاق قديم</b>
        </div>";
        echo json_encode($data);
        exit();
    }

    // Adjust money
    if ($money_out > ($wanted * -1)) {
        $money_out = $wanted * -1;
    }

    /* ------------------------ ERRORS FOUND ------------------------ */
    if (!empty($error)) {
        $data["error"] = $error;
        echo json_encode($data);
        exit();
    }

    /* ------------------------ PREVENT DOUBLE SANAD ------------------------ */

    $maxN = $conn->prepare("
        SELECT out_id, audate 
        FROM outvoice 
        WHERE out_id = (
            SELECT MAX(out_id) 
            FROM outvoice 
            WHERE contract_id = ? AND branch = ?
        )
    ");
    $maxN->execute([$contract_id, $branch]);

    if ($maxN->rowCount() > 0) {
        $row = $maxN->fetch(PDO::FETCH_ASSOC);
        $lastTime = strtotime($row['audate']);
        $nowTime  = strtotime(date("Y-m-d H:i:s"));

        if (($nowTime - $lastTime) < 40) {
            $data["out_id"] = $row['out_id'];
            $data["msg"] = "<div class='alert alert-success'><b>تم تسجيل سند الصرف بنجاح</b></div>";
            echo json_encode($data);
            exit();
        }
    }

    /* ------------------------ NEW OUT_ID ------------------------ */

    $maxsql = $conn->query("SELECT MAX(out_id) AS maxd FROM outvoice");
    $maxD = ($maxsql->rowCount() > 0)
            ? $maxsql->fetch(PDO::FETCH_ASSOC)['maxd'] + 1
            : 1;

    $money_out = round($money_out, 2);

    $sanad = $conn->prepare("
        INSERT INTO outvoice(out_id, contract_id, sanad_out, money_out, payOutMethod, iban, comm, father, branch)
        VALUES(?,?,?,?,?,?,?,?,?)
    ");

    $ok = $sanad->execute([
        $maxD,
        $contract_id,
        $sanad_date,
        $money_out,
        $payOutMethod,
        $iban,
        $comm,
        $father,
        $branch
    ]);

    if ($ok) {
        $data["out_id"] = $maxD;
        $data["msg"] = "<div class='alert alert-success'>
            <b>تم تسجيل سند الصرف بنجاح</b>
        </div>";

        auto_close($conn, $contract_id);

    } else {
        $data["msg"] = "<div class='alert alert-danger'><b>يوجد خطأ في تسجيل البيانات</b></div>";
    }

    echo json_encode($data);
}
