<?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;
}

$transfer_id = $_POST['transfer_id'] ?? null;

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

$conn = db();

/**
 * =========================================
 * FETCH TRANSFER
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT * FROM transfers 
    WHERE id = ? AND user_id = ? AND status IN ('processing','otp_verified')
");
$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 ready or invalid"
    ]);
    exit;
}

/**
 * =========================================
 * FETCH USER ACCOUNT
 * =========================================
 */
$stmt = $conn->prepare("SELECT balance, currency, full_name, email FROM users WHERE id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

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

/**
 * =========================================
 * CHECK TOKEN COMPLETION
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT COUNT(*) as done_count 
    FROM transfer_tokens 
    WHERE transfer_id = ? AND user_id = ? AND status = 'used'
");
$stmt->bind_param("ii", $transfer_id, $user_id);
$stmt->execute();
$tokenCheck = $stmt->get_result()->fetch_assoc();

if ($tokenCheck['done_count'] < 1) {
    echo json_encode([
        "status" => false,
        "message" => "Token verification incomplete"
    ]);
    exit;
}

/**
 * =========================================
 * CALCULATE TOTAL DEDUCTION
 * =========================================
 */
$total_deduction = $transfer['amount'] + $transfer['fee'];

if ($total_deduction > $user['balance']) {
    echo json_encode([
        "status" => false,
        "message" => "Insufficient balance for final processing"
    ]);
    exit;
}

/**
 * =========================================
 * DEBIT USER
 * =========================================
 */
$new_balance = $user['balance'] - $total_deduction;

$stmt = $conn->prepare("UPDATE users SET balance=? WHERE id=?");
$stmt->bind_param("di", $new_balance, $user_id);
$stmt->execute();

/**
 * =========================================
 * CREDIT RECIPIENT (SIMPLIFIED LOGIC)
 * NOTE: assumes internal users table match
 * =========================================
 */
$stmt = $conn->prepare("
    SELECT id, balance, email, full_name 
    FROM users 
    WHERE account_number = ?
");
$stmt->bind_param("s", $transfer['account_no']);
$stmt->execute();
$recipient = $stmt->get_result()->fetch_assoc();

if ($recipient) {
    $recipient_new_balance = $recipient['balance'] + $transfer['amount'];

    $stmt = $conn->prepare("UPDATE users SET balance=? WHERE id=?");
    $stmt->bind_param("di", $recipient_new_balance, $recipient['id']);
    $stmt->execute();
}

/**
 * =========================================
 * MARK TRANSFER COMPLETE
 * =========================================
 */
$stmt = $conn->prepare("
    UPDATE transfers 
    SET status='completed', updated_at=NOW() 
    WHERE id=?
");
$stmt->bind_param("i", $transfer_id);
$stmt->execute();

/**
 * =========================================
 * EMAIL NOTIFICATIONS
 * =========================================
 */

// Sender email
$subject1 = "DemoBank Debit Alert";
$message1 = "
<html>
<body>
<h2>Debit Alert</h2>
<p>Dear {$user['full_name']},</p>
<p>Your transfer of <b>{$user['currency']}{$transfer['amount']}</b> has been completed.</p>
<p>Fee charged: <b>{$user['currency']}{$transfer['fee']}</b></p>
<p>Total deducted: <b>{$user['currency']}{$total_deduction}</b></p>
<br>
<p>Thank you for banking with DemoBank.</p>
</body>
</html>
";

sendEmail($user['email'], $subject1, $message1);

// Recipient email (if exists)
if (!empty($recipient)) {

    $subject2 = "DemoBank Credit Alert";
    $message2 = "
    <html>
    <body>
    <h2>Credit Alert</h2>
    <p>Dear {$recipient['full_name']},</p>
    <p>You have received <b>{$user['currency']}{$transfer['amount']}</b>.</p>
    <br>
    <p>DemoBank Transfer System</p>
    </body>
    </html>
    ";

    sendEmail($recipient['email'], $subject2, $message2);
}

/**
 * =========================================
 * RESPONSE
 * =========================================
 */
echo json_encode([
    "status" => true,
    "message" => "Transfer completed successfully",
    "new_balance" => $new_balance
]);