<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../actions/admin_auth.php';

header('Content-Type: application/json');

/*
---------------------------------------
VALIDATION
---------------------------------------
*/
$required = ['id','account_number','type','amount','status','created_at'];
foreach ($required as $field) {
    if (!isset($_POST[$field]) || $_POST[$field] === '') {
        echo json_encode([
            "status" => "error",
            "message" => "Missing required field: $field"
        ]);
        exit;
    }
}

/*
---------------------------------------
SANITIZE INPUT
---------------------------------------
*/
$transaction_id   = (int) $_POST['id'];
$account_number   = trim($_POST['account_number']);
$type             = strtolower(trim($_POST['type']));
$amount           = (float) $_POST['amount'];
$status           = strtolower(trim($_POST['status']));
$reference        = trim($_POST['reference'] ?? null);
$description      = trim($_POST['description'] ?? null);

/* Fix datetime-local → MySQL datetime */
$created_at = date('Y-m-d H:i:s', strtotime($_POST['created_at']));

/*
---------------------------------------
FETCH TRANSACTION
---------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT user_id, amount, type, status 
    FROM transactions 
    WHERE id = ?
");
$stmt->execute([$transaction_id]);
$trx = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$trx) {
    echo json_encode([
        "status" => "error",
        "message" => "Transaction not found"
    ]);
    exit;
}

$user_id    = (int) $trx['user_id'];
$old_amount = (float) $trx['amount'];
$old_type   = strtolower($trx['type']);
$old_status = strtolower($trx['status']);

/*
---------------------------------------
FETCH USER BALANCE
---------------------------------------
*/
$stmt = $pdo->prepare("SELECT account_balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode([
        "status" => "error",
        "message" => "User not found"
    ]);
    exit;
}

$new_balance = (float) $user['account_balance'];

/*
---------------------------------------
BEGIN TRANSACTION
---------------------------------------
*/
$pdo->beginTransaction();

try {

    /*
    ---------------------------------------
    REVERSE OLD SUCCESS
    ---------------------------------------
    */
    if ($old_status === 'successful') {
        if ($old_type === 'deposit') {
            $new_balance -= $old_amount;
        } else {
            $new_balance += $old_amount;
        }
    }

    /*
    ---------------------------------------
    APPLY NEW SUCCESS
    ---------------------------------------
    */
    if ($status === 'successful') {
        if ($type === 'deposit') {
            $new_balance += $amount;
        } else {
            if ($new_balance < $amount) {
                throw new Exception('Insufficient balance for this update');
            }
            $new_balance -= $amount;
        }
    }

    /*
    ---------------------------------------
    UPDATE USER BALANCE
    ---------------------------------------
    */
    $stmt = $pdo->prepare("
        UPDATE users 
        SET account_balance = ? 
        WHERE id = ?
    ");
    $stmt->execute([$new_balance, $user_id]);

    /*
    ---------------------------------------
    UPDATE TRANSACTION HISTORY
    ---------------------------------------
    */
    $stmt = $pdo->prepare("
        UPDATE transactions SET
            account_number = ?,
            type = ?,
            amount = ?,
            status = ?,
            reference = ?,
            description = ?,
            created_at = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $account_number,
        $type,
        $amount,
        $status,
        $reference,
        $description,
        $created_at,
        $transaction_id
    ]);

    /*
    ---------------------------------------
    COMMIT
    ---------------------------------------
    */
    $pdo->commit();

    echo json_encode([
        "status" => "success",
        "message" => "Transaction history updated successfully",
        "new_balance" => number_format($new_balance, 2)
    ]);
    exit;

} catch (Exception $e) {

    $pdo->rollBack();

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