<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) session_start();

$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$txn_id = filter_var($_POST['transaction_id'] ?? 0, FILTER_VALIDATE_INT);
if (!$txn_id) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid transaction ID']);
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT id, transaction_ref, status FROM transactions WHERE id = :id LIMIT 1");
    $stmt->bindParam(':id', $txn_id, PDO::PARAM_INT);
    $stmt->execute();
    $txn = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$txn) {
        echo json_encode(['status' => '0', 'msg' => 'Transaction not found']);
        exit();
    }

    if ($txn['status'] !== 'pending') {
        echo json_encode(['status' => '0', 'msg' => 'Only pending transactions can be cancelled']);
        exit();
    }

    $stmt = $pdo->prepare("UPDATE transactions SET status = 'cancelled', updated_at = NOW() WHERE id = :id");
    $stmt->bindParam(':id', $txn_id, PDO::PARAM_INT);
    $stmt->execute();

    echo json_encode([
        'status' => '1',
        'msg'    => 'Transaction ' . $txn['transaction_ref'] . ' has been cancelled.'
    ]);

} catch (PDOException $e) {
    echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
}
?>