<?php
declare(strict_types=1);
session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php';

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

$sender_id = (int)$_SESSION['user_id'];
$type = trim(strtolower($_POST['type'] ?? ''));
$recipient_account = trim($_POST['recipient_account'] ?? '');
$amount = (float)($_POST['amount'] ?? 0);
$pin = trim($_POST['transfer_pin'] ?? '');
$description = trim($_POST['description'] ?? '');
$otp      = trim((string)($_POST['otp'] ?? ''));

if ($type === '' || $recipient_account === '' || $amount <= 0 || $pin === '' || $otp === '') {
    echo json_encode(['status'=>'error','message'=>'Missing required fields.']);
    exit;
}

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

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

// Ensure account active
if ((int)$sender['is_verified'] === 0) {
    echo json_encode(['status'=>'error','message'=>'Your account is not active or verified.']);
    exit;
}


// Restricted User
if (strtolower($sender['tstatus']) !== 'active') {
    echo json_encode(['status'=>'error','message'=>'You cannot make transfer at the moment. Please hold for while or contact your bank.']);
    exit;
}

// Ensure debit card enabled
if ((int)$sender['has_card'] !== 1) {
    echo json_encode(['status'=>'error','message'=>'You must have an active debit card to transfer.']);
    exit;
}

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

// Verify PIN
$storedPin = $sender['transfer_pin'];
$pinOk = ($storedPin !== '' && (password_verify($pin, $storedPin) || $storedPin === $pin));

if (!$pinOk) {
    echo json_encode(['status'=>'error','message'=>'Invalid Transfer PIN.']);
    exit;
}

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

// Generate unique reference
function generateTransactionReference($pdo) {
    do {
        $ref = 'TXN' . strtoupper(bin2hex(random_bytes(6)));
        $q = $pdo->prepare("SELECT id FROM transactions WHERE reference = ? LIMIT 1");
        $q->execute([$ref]);
    } while ($q->fetch());
    return $ref;
}

$pdo->beginTransaction();
try {
    $notp = rand(1000, 9999);

    // Lock sender balance
    $stmt = $pdo->prepare("SELECT account_balance FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$sender_id]);
    $sender_balance = (float)$stmt->fetchColumn();

    if ($sender_balance < $amount) {
        $pdo->rollBack();
        echo json_encode(['status'=>'error','message'=>'Insufficient Funds.']);
        exit;
    }

    // Check internal recipient
    $stmt = $pdo->prepare("SELECT * FROM users WHERE account_number = ? LIMIT 1 FOR UPDATE");
    $stmt->execute([$recipient_account]);
    $recipient = $stmt->fetch(PDO::FETCH_ASSOC);

    $is_internal = $recipient ? true : false;
    $reference = generateTransactionReference($pdo);

    // Deduct sender balance
    $new_sender_balance = $sender_balance - $amount;
    $stmt = $pdo->prepare("UPDATE users SET otp = '$notp', account_balance = ?, updated_at = NOW() WHERE id = ?");
    $stmt->execute([$new_sender_balance, $sender_id]);

    // Log sender transaction (DEBIT)
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, account_number, type, amount, description, reference, status, created_at)
                           VALUES (?, ?, 'debit', ?, ?, ?, 'successful', NOW())");
    $stmt->execute([
        $sender_id,
        $recipient_account,
        $amount,
        "Transfer to ".$recipient['firstname']." ".$recipient['lastname']." | Acct: ".$recipient_account." | Note: ".$description,
        $reference
    ]);

    // If internal recipient → Credit and Log
    if ($is_internal) {
        $new_recipient_balance = (float)$recipient['account_balance'] + $amount;

        $stmt = $pdo->prepare("UPDATE users SET account_balance = ?, updated_at = NOW() WHERE id = ?");
        $stmt->execute([$new_recipient_balance, $recipient['id']]);

        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, account_number, type, amount, description, reference, status, created_at)
                               VALUES (?, ?, 'credit', ?, ?, ?, 'successful', NOW())");
        $stmt->execute([
            $recipient['id'],
            $sender['account_number'],
            $amount,
            "Received from ".$sender['firstname']." ".$sender['lastname']." | Acct: ".$sender['account_number']." | Note:".$description,
            $reference
        ]);
    }

$s_currency = $sender['currency'];
$r_currency = $recipient['currency'];
    $pdo->commit();

/* =======================
   EMAIL ALERT: SENDER (DEBIT)
   ======================= */
sendMail(
  $sender['email'],
  "{$s_currency}{$amount} Debit Alert - 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;">Debit Alert</h2>
      </div>

      <div style="background: #fff; padding: 20px; border-radius: 8px; margin-top: 15px;">
          <p style="margin: 4px 0;"><strong>Account Name:</strong> '.$sender['firstname'].' '.$sender['lastname'].'</p>
          <p style="margin: 4px 0;"><strong>Account Number:</strong> '.$sender['account_number'].'</p>
          <p style="margin: 4px 0;"><strong>Amount Debited:</strong> '.$s_currency.''.$amount.'</p>
          <p style="margin: 4px 0;"><strong>Transaction Type:</strong> Transfer</p>
          <p style="margin: 4px 0;"><strong>Recipient Account:</strong> '.$recipient_account.'</p>
          <p style="margin: 4px 0;"><strong>Description:</strong> '.$description.'</p>
          <p style="margin: 4px 0;"><strong>Reference:</strong> '.$reference.'</p>
          <p style="margin: 4px 0;"><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>
  '
);

/* =======================
   EMAIL ALERT: RECIPIENT (CREDIT)
   Only if internal transfer
   ======================= */
if ($is_internal) {
  sendMail(
    $recipient['email'],
    "{$r_currency}{$amount} Credit Alert - Bmellonglobal",
    '
    <div style="font-family: Arial, sans-serif; max-width: 600px; margin: auto; background: #f5f6fa; padding: 20px; border-radius: 8px;">
        
        <div style="background: #203a43; padding: 15px; border-radius: 8px; text-align: center; color: white;">
            <h2 style="margin: 0;">Credit Alert</h2>
        </div>

        <div style="background: #fff; padding: 20px; border-radius: 8px; margin-top: 15px;">
            <p style="margin: 4px 0;"><strong>Account Name:</strong> '.$recipient['firstname'].' '.$recipient['lastname'].'</p>
            <p style="margin: 4px 0;"><strong>Account Number:</strong> '.$recipient['account_number'].'</p>
            <p style="margin: 4px 0;"><strong>Amount Credited:</strong> '.$r_currency.''.$amount.'</p>
            <p style="margin: 4px 0;"><strong>Received From:</strong> '.$sender['firstname'].' '.$sender['lastname'].' ('.$sender['account_number'].')</p>
            <p style="margin: 4px 0;"><strong>Description:</strong> '.$description.'</p>
            <p style="margin: 4px 0;"><strong>Reference:</strong> '.$reference.'</p>
            <p style="margin: 4px 0;"><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;


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

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