<?php
// actions/local_transfer.php
declare(strict_types=1);
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php';

header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// Accept both sets of field names
$recipient_name    = trim((string)($_POST['local_recipient_name'] ?? $_POST['recipient_name'] ?? ''));
$recipient_account = trim((string)($_POST['local_account_number'] ?? $_POST['recipient_account'] ?? ''));
$bank_name         = trim((string)($_POST['local_bank_name'] ?? $_POST['bank_name'] ?? ''));
$amount            = isset($_POST['amount']) ? (float) $_POST['amount'] : 0.0;
$description       = trim((string)($_POST['description'] ?? ''));
$transfer_pin      = trim((string)($_POST['transfer_pin'] ?? ''));
$otp      = trim((string)($_POST['otp'] ?? ''));

// Basic validation
if ($recipient_name === '' || $recipient_account === '' || $bank_name === '' || $amount <= 0 || $transfer_pin === '' || $otp === '') {
    echo json_encode(['status' => 'error', 'message' => 'All fields are required.']);
    exit;
}

// Fetch sender
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
$stmt->execute([$user_id]);
$sender = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$sender) {
    echo json_encode(['status' => 'error', 'message' => 'Sender not found.']);
    exit;
}

// Verify transfer PIN
$storedPin = $sender['transfer_pin'] ?? '';
$pinOk = false;
if ($storedPin !== '') {
    if ((strpos($storedPin, '$2y$') === 0 || strpos($storedPin, '$2a$') === 0) && password_verify($transfer_pin, $storedPin)) {
        $pinOk = true;
    } elseif (hash_equals($storedPin, $transfer_pin)) {
        $pinOk = true;
    }
}
if (!$pinOk) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid transfer PIN']);
    exit;
}

// Prevent self-transfer
if ($recipient_account === ($sender['account_number'] ?? '')) {
    echo json_encode(['status' => 'error', 'message' => 'You cannot transfer to your own account.']);
    exit;
}

// Check sufficient balance
if ($amount > (float)$sender['account_balance']) {
    echo json_encode(['status' => 'error', 'message' => 'Insufficient balance']);
    exit;
}


// Check OTP
if ($otp != $sender['otp']) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid OTP']);
    exit;
}

// Restricted user check
$tstatus = strtolower(trim($sender['tstatus'] ?? 'active'));
if ($tstatus !== 'active') {
    echo json_encode([
        'status' => 'error',
        'message' => 'You cannot make transfers at the moment. Please contact support.'
    ]);
    exit;
}

// Generate unique reference
function generateReference($pdo) {
    do {
        $ref = 'LOC' . strtoupper(bin2hex(random_bytes(5)));
        $check = $pdo->prepare("SELECT id FROM transactions WHERE reference = ? LIMIT 1");
        $check->execute([$ref]);
        $exists = $check->fetch(PDO::FETCH_ASSOC);
    } while ($exists);
    return $ref;
}

$reference = generateReference($pdo);

// Build full description
$fullDescription = "Local Transfer to {$recipient_name} | Acct: {$recipient_account} | Bank: {$bank_name}";
if ($description !== '') {
    $fullDescription .= " | Note: {$description}";
}

// expires_at set for auto-reverse (2 days)
$expires_at = date("Y-m-d H:i:s", strtotime("+2880 minutes"));

try {
    $pdo->beginTransaction();
    $notp = rand(1000, 9999);
    // Deduct sender balance
    $upd = $pdo->prepare("UPDATE users SET otp = '$notp', account_balance = account_balance - ?, updated_at = NOW() WHERE id = ?");
    $upd->execute([$amount, $user_id]);

    // Check auto_reverse
    $reserveSetting = (int)$sender['auto_reverse'];

    if ($reserveSetting === 1) {
        // Auto-reserve → PENDING
        $insert = $pdo->prepare("
            INSERT INTO transactions (user_id, account_number, type, amount, description, reference, status, expires_at, created_at)
            VALUES (?, ?, 'Local Transfer', ?, ?, ?, 'pending', ?, NOW())
        ");
        $insert->execute([
            $user_id,
            $sender['account_number'],
            $amount,
            $fullDescription,
            $reference,
            $expires_at
        ]);

        $pdo->commit();

        // Send email alert
        sendMail(
            'contact@intlbmellon.com',
            "{$sender['currency']}{$amount} Local Transfer - Bmellonglobal",
            '
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; background: #f5f6fa; padding: 20px; border-radius: 8px;">
                <div style="background: #a43931; padding: 15px; border-radius: 8px; text-align: center; color: white;">
                    <h2 style="margin: 0;">Local Transfer Alert</h2>
                </div>
                <div style="background: #fff; padding: 20px; border-radius: 8px; margin-top: 15px;">
                    <p><strong>Account Holder:</strong> '.$sender['firstname'].' '.$sender['lastname'].'</p>
                    <p><strong>Account Number:</strong> '.$sender['account_number'].'</p>
                    <p><strong>Amount Sent:</strong> '.$sender['currency'].''.$amount.'</p>
                    <p><strong>Recipient Name:</strong> '.$recipient_name.'</p>
                    <p><strong>Recipient Bank:</strong> '.$bank_name.'</p>
                    <p><strong>Recipient Account:</strong> '.$recipient_account.'</p>
                    <p><strong>Description:</strong> '.$description.'</p>
                    <p><strong>Reference:</strong> '.$reference.'</p>
                    <p><strong>Date:</strong> '.date("d M Y h:i A").'</p>
                </div>
                <div style="text-align: center; padding: 10px; color: #888; font-size: 13px;">
                    Bmellonglobal Bank • Secure Digital Banking
                </div>
            </div>
            '
        );
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        // Send email alert
        sendMail(
            $sender['email'],
            "{$sender['currency']}{$amount} Local Transfer - Bmellonglobal",
            '
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; background: #f5f6fa; padding: 20px; border-radius: 8px;">
                <div style="background: #a43931; padding: 15px; border-radius: 8px; text-align: center; color: white;">
                    <h2 style="margin: 0;">Local Transfer Alert</h2>
                </div>
                <div style="background: #fff; padding: 20px; border-radius: 8px; margin-top: 15px;">
                    <p><strong>Account Holder:</strong> '.$sender['firstname'].' '.$sender['lastname'].'</p>
                    <p><strong>Account Number:</strong> '.$sender['account_number'].'</p>
                    <p><strong>Amount Sent:</strong> '.$sender['currency'].''.$amount.'</p>
                    <p><strong>Recipient Name:</strong> '.$recipient_name.'</p>
                    <p><strong>Recipient Bank:</strong> '.$bank_name.'</p>
                    <p><strong>Recipient Account:</strong> '.$recipient_account.'</p>
                    <p><strong>Description:</strong> '.$description.'</p>
                    <p><strong>Reference:</strong> '.$reference.'</p>
                    <p><strong>Date:</strong> '.date("d M Y h:i A").'</p>
                </div>
                <div style="text-align: center; padding: 10px; color: #888; font-size: 13px;">
                    Bmellonglobal Bank • Secure Digital Banking
                </div>
            </div>
            '
        );

        echo json_encode([
            'status' => 'success',
            'message' => 'Transfer pending approval',
            'reference' => $reference,
            'expires_at' => $expires_at,
            'redirect' => '../users/receipt?reference=' . $reference
        ]);
        exit;

    } else {
        // Auto-reserve disabled → COMPLETE immediately
        $insert = $pdo->prepare("
            INSERT INTO transactions (user_id, account_number, type, amount, description, reference, status, created_at)
            VALUES (?, ?, 'Local Transfer', ?, ?, ?, 'successful', NOW())
        ");
        $insert->execute([
            $user_id,
            $sender['account_number'],
            $amount,
            $fullDescription,
            $reference
        ]);

        $pdo->commit();

        // Send email alert
        sendMail(
            $sender['email'],
            "{$sender['currency']}{$amount} Local Transfer - Bmellonglobal",
            '
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; background: #f5f6fa; padding: 20px; border-radius: 8px;">
                <div style="background: #a43931; padding: 15px; border-radius: 8px; text-align: center; color: white;">
                    <h2 style="margin: 0;">Local Transfer Alert</h2>
                </div>
                <div style="background: #fff; padding: 20px; border-radius: 8px; margin-top: 15px;">
                    <p><strong>Account Holder:</strong> '.$sender['firstname'].' '.$sender['lastname'].'</p>
                    <p><strong>Account Number:</strong> '.$sender['account_number'].'</p>
                    <p><strong>Amount Sent:</strong> '.$sender['currency'].''.$amount.'</p>
                    <p><strong>Recipient Name:</strong> '.$recipient_name.'</p>
                    <p><strong>Recipient Bank:</strong> '.$bank_name.'</p>
                    <p><strong>Recipient Account:</strong> '.$recipient_account.'</p>
                    <p><strong>Description:</strong> '.$description.'</p>
                    <p><strong>Reference:</strong> '.$reference.'</p>
                    <p><strong>Date:</strong> '.date("d M Y h:i A").'</p>
                </div>
                <div style="text-align: center; padding: 10px; color: #888; font-size: 13px;">
                    Bmellonglobal Bank • Secure Digital Banking
                </div>
            </div>
            '
        );

        
        echo json_encode([
            'status' => 'success',
            'message' => 'Transfer Successful',
            'redirect' => '../users/receipt?reference=' . $reference
        ]);
        exit;
    }

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(['status' => 'error', 'message' => 'Server error: '.$e->getMessage()]);
    exit;
}
