<?php
require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/session.php";
require_once __DIR__ . "/../includes/mailer.php";

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

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

// Ensure user is logged in
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    echo json_encode([
        "status" => false,
        "message" => "Unauthorized access"
    ]);
    exit;
}

// Get transfer ID
$transfer_id = $_POST['transfer_id'] ?? null;

if (!$transfer_id) {
    echo json_encode([
        "status" => false,
        "message" => "Transfer ID required"
    ]);
    exit;
}

$conn = db();

// Check if transfer belongs to user and is cancellable
$stmt = $conn->prepare("
    SELECT id, status, amount, currency
    FROM transfers
    WHERE id = ? AND user_id = ? AND status IN ('pending','otp_verified','processing')
");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$transfer = $stmt->get_result()->fetch_assoc();

if (!$transfer) {
    echo json_encode([
        "status" => false,
        "message" => "Transfer not found or cannot be cancelled"
    ]);
    exit;
}

// Update transfer status to cancelled
$stmt = $conn->prepare("UPDATE transfers SET status='cancelled', updated_at=NOW() WHERE id=?");
$stmt->bind_param("i", $transfer_id);
$stmt->execute();

// Optional: mark any associated tokens as expired/cancelled
$stmt = $conn->prepare("UPDATE transfer_tokens SET status='expired' WHERE transfer_id=?");
$stmt->bind_param("i", $transfer_id);
$stmt->execute();

// Send cancellation notification email to user
$stmt = $conn->prepare("SELECT email, full_name FROM users WHERE id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if ($user) {
    $subject = "DemoBank Transfer Cancelled";
    $message = "
    <html>
    <body>
        <h2>Transfer Cancelled</h2>
        <p>Hello <b>{$user['full_name']}</b>,</p>
        <p>Your transfer (ID: {$transfer_id}) has been successfully cancelled.</p>
        <p>If this was not you, please contact support immediately.</p>
        <br>
        <p>DemoBank Team</p>
    </body>
    </html>
    ";
    sendEmail($user['email'], $subject, $message);
}

echo json_encode([
    "status" => true,
    "message" => "Transfer cancelled successfully"
]);