<?php
session_start();
require 'db.php';
header('Content-Type: application/json');
if (!isset($_SESSION['co_id'])) {
    echo json_encode(["status" => "error", "message" => "Unauthorized"]);
    exit;
}

$coid  = $_SESSION['co_id'];
$userid  = $_SESSION['user_id'];

$acc_id      = $_POST['acc2_id'];
$date  = $_POST['date_close'];
$credit  = $_POST['bal_credit'];
$debit  = $_POST['adj_debit'];
$t_type  ="csh_close";
$t_status  ="Confirmed";
$t_copy  ="O";

if (empty($acc_id)) {
    echo json_encode(["status" => "error", "message" => "Select account to adjust"]);
    exit;
}


if (empty($credit) ) {
    echo json_encode(["status" => "error", "message" => "Enter closing cash  amount"]);
    exit;
}


$stmt = $pdo->prepare("
    INSERT INTO transactions (co_id, t_date, t_copy, t_type, t_cr, t_credit, t_debit, t_status,t_entry_by )
    VALUES (?, ?, ?, ?,?,?,?,?,?)
");

 // Update status
                    $stmt3 = $pdo->prepare("
                    UPDATE transactions t
                    SET t.t_status = 'Confirmed'
                    WHERE 
                      t.t_date = ?
                      AND t.t_type = 'csh_close'
                      AND t.co_id = ?
                      AND EXISTS (
                        SELECT 1
                        FROM permissions p
                        LEFT JOIN accounts u ON t.t_cr = u.id
                        WHERE 
                          p.co_id = t.co_id
                          AND p.user_id = ?
                          AND p.pm_acc_lvl IN (0,1,2,6,7)
                          AND (
                            (t.t_cr = p.pm_acc_id AND p.pm_acc_id <> '')
                            OR
                            (u.acc_categ = p.pm_acc_categ AND p.pm_acc_id = '')
                          )
                      );
                    ");
                    

try {

    $pdo->beginTransaction();
    
    $stmt->execute([$coid, $date, $t_copy, $t_type, $acc_id, $credit, $debit, $t_status,$userid]);
    
    $stmt3->execute([$date, $coid, $userid]);
    
    $pdo->commit();

    echo json_encode(["status" => "success"]);

} catch (Exception $e) {

    $pdo->rollBack();

    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
}
