<?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'];

session_write_close();

$acc_id      = $_POST['acc1_id'];
$date  = $_POST['date_adj'];
$credit  = $_POST['adj_credit'];
$debit  = $_POST['adj_debit'];
$t_type  ="csh_adj";
$t_status  ="Confirmed";


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

if (!empty($credit) && !empty($debit)) {
    echo json_encode(["status" => "error", "message" => "A Credit And Debit cannot be submitted at the same time. Please Submit one at a time"]);
    exit;
}

if (empty($credit) && empty($debit)) {
    echo json_encode(["status" => "error", "message" => "Submit a Credit Or Debit amount. Both cannot be empty"]);
    exit;
}

if (!empty($credit)) {
    $t_copy  ="O";
}

else if (!empty($debit)) {
    $t_copy  ="D";
}

$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()
    ]);
}
