<?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 (?, ?, ?, ?,?,?,?,?,?)
");

try {

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

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

} catch (Exception $e) {

    $pdo->rollBack();

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