<?php
ob_start();
session_start();
include '../functions.php';

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

if (!isset($_SESSION['user_id']) || !isset($_SESSION['email'])) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Session expired. Please log in again.']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$otp   = trim($input['otp'] ?? '');

if ($otp === '' || strlen($otp) !== 6 || !ctype_digit($otp)) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Please enter a valid 6-digit OTP.']);
    exit;
}

$email = $_SESSION['email'];

// Fetch stored OTP from DB
$stmt = $connect->prepare("SELECT otp FROM users WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$row || $otp !== (string)$row['otp']) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Incorrect or expired OTP. Please try again.']);
    exit;
}

// Pull transfer data from session
$amount        = (float)($_SESSION['lt_amount']        ?? 0);
$accountname   = $_SESSION['lt_accountname']           ?? '';
$accountnumber = $_SESSION['lt_accountnumber']         ?? '';
$bankname      = $_SESSION['lt_bankname']              ?? '';
$accounttype   = $_SESSION['lt_accounttype']           ?? '';
$description   = $_SESSION['lt_description']           ?? '';
$cot_code      = $_SESSION['lt_cot_code']              ?? '';
$tax_code      = $_SESSION['lt_tax_code']              ?? '';

// Server-side balance validation
$balance = (float)(getUserDetails('balance', $email) ?: 0);
if ($amount <= 0 || $amount > $balance) {
    ob_end_clean(); echo json_encode(['success' => false, 'message' => 'Insufficient balance or invalid transfer amount.']);
    exit;
}

$acc_no      = (string)(getUserDetails('acc_no', $email) ?? '');
$new_balance = $balance - $amount;
$date        = date('Y-m-d H:i:s');

$txn_details  = "Local transfer to {$accountname} ({$bankname})";
if ($description !== '') {
    $txn_details .= " | {$description}";
}
$prev_bal_str = (string)$balance;
$new_bal_str  = (string)$new_balance;

try {
    $connect->begin_transaction();

    // Deduct balance and clear OTP
    $stmt = $connect->prepare("UPDATE users SET balance = ?, otp = NULL WHERE email = ?");
    $stmt->bind_param("ds", $new_balance, $email);
    $stmt->execute();
    $stmt->close();

    // Expire COT code
    if ($cot_code !== '' && $acc_no !== '') {
        $stmt = $connect->prepare("UPDATE cot_codes SET status = 'Expired', used_by = ? WHERE cot_code = ?");
        $stmt->bind_param("ss", $acc_no, $cot_code);
        $stmt->execute();
        $stmt->close();
    }

    // Expire Tax code
    if ($tax_code !== '' && $acc_no !== '') {
        $stmt = $connect->prepare("UPDATE tax_codes SET status = 'Expired', used_by = ? WHERE tax_code = ?");
        $stmt->bind_param("ss", $acc_no, $tax_code);
        $stmt->execute();
        $stmt->close();
    }

    // Insert transaction record
    $stmt = $connect->prepare(
        "INSERT INTO transactions
            (account_number, transaction_type, amount, prev_bal, new_bal, new_balance,
             status, transaction_details, account_type, acc_type,
             receiver_fullname, other_bank_name, name, stat, date_added)
         VALUES (?, 'Debit', ?, ?, ?, ?, 'Success', ?, ?, ?, ?, ?, ?, 'Local Transfer', ?)"
    );
    $stmt->bind_param(
        "sdssssssssss",
        $acc_no, $amount, $prev_bal_str, $new_bal_str, $new_bal_str,
        $txn_details, $accounttype, $accounttype,
        $accountname, $bankname, $accountname, $date
    );
    $stmt->execute();
    $stmt->close();

    $connect->commit();

} catch (Exception $e) {
    $connect->rollback();
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Transaction failed: ' . $e->getMessage()]);
    exit;
}

// Save receipt data for the receipt page
$_SESSION['lt_receipt'] = [
    'amount'        => $amount,
    'accountname'   => $accountname,
    'accountnumber' => $accountnumber,
    'bankname'      => $bankname,
    'accounttype'   => $accounttype,
    'description'   => $description,
    'date'          => $date,
    'prev_balance'  => $balance,
    'new_balance'   => $new_balance,
    'acc_no'        => $acc_no,
];

// Send debit notification email (non-critical, outside transaction)
$fullname = (string)(getUserDetails('fullname', $email) ?? 'Customer');
$sitename = (string)(getSiteConfig('sitename') ?? 'CreditPay');
$sitemail = (string)(getSiteConfig('sitemail') ?? '');
$curr     = $_SESSION['currency'] ?? 'USD';
$sym      = currencySymbol($curr);

$subject = "Debit Alert — {$sitename}";
$body    = "Dear {$fullname},\r\n\r\n"
         . "A debit transaction has been processed on your account:\r\n\r\n"
         . "  Amount        : {$sym}" . number_format($amount, 2) . "\r\n"
         . "  Recipient     : {$accountname}\r\n"
         . "  Bank          : {$bankname}\r\n"
         . "  Account No    : {$accountnumber}\r\n"
         . "  Account Type  : {$accounttype}\r\n"
         . "  Description   : " . ($description ?: '—') . "\r\n"
         . "  Date          : " . date('M d, Y H:i', strtotime($date)) . "\r\n"
         . "  New Balance   : {$sym}" . number_format($new_balance, 2) . "\r\n\r\n"
         . "If you did not initiate this transaction, contact us immediately at {$sitemail}.\r\n\r\n"
         . "— {$sitename}";
$headers = "From: {$sitename} <{$sitemail}>\r\nContent-type: text/plain; charset=UTF-8";

@mail($email, $subject, $body, $headers);

// Clear transfer session keys
foreach (['lt_amount','lt_accountname','lt_accountnumber','lt_bankname','lt_accounttype',
          'lt_routing','lt_swift','lt_description','lt_cot_code','lt_tax_code'] as $k) {
    unset($_SESSION[$k]);
}

ob_end_clean();
echo json_encode(['success' => true, 'redirect' => 'receipt']);
