<?php
declare(strict_types=1);
session_start();
ini_set('display_errors', '1'); error_reporting(E_ALL);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';
require_once __DIR__ . '/../includes/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header('Location: dashboard.php'); exit; }

// ... (Your KYC, CSRF, and data validation code remains the same) ...
// The code from line 13 up to line 41 of your original file should remain here.

// --------------------------------------------------------------------------------
// NEW LOGIC STARTS HERE: PREPARE DATA FOR AUTHORIZATION
// --------------------------------------------------------------------------------

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->beginTransaction();

    // Lock sender to check balance (Locking is essential for banking logic)
    $stmt = $pdo->prepare("SELECT id, balance_cents, transaction_pin_hash FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$from_uid]);
    $sender = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$sender) throw new RuntimeException('Sender not found');
    
    // CHECK FOR PIN EXISTENCE
    if (empty($sender['transaction_pin_hash'])) {
        // Redirect to PIN setup if not set (Highly recommended)
        throw new RuntimeException('Transaction PIN must be set before transfer.');
    }

    // Lock recipient (just to ensure account exists and prevent self-transfer)
    $stmt = $pdo->prepare("SELECT id FROM users WHERE account_number = ? FOR UPDATE");
    $stmt->execute([$to_acct]);
    $rec = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$rec) throw new RuntimeException('Recipient not found');

    if ((int)$rec['id'] === (int)$sender['id']) {
        throw new RuntimeException('Cannot transfer to your own account');
    }

    // Final Balance Check
    if ((int)$sender['balance_cents'] < $amount_cents) throw new RuntimeException('Insufficient funds');
    
    // SAVE PENDING TRANSACTION DETAILS (YOU MAY NEED A NEW DB TABLE FOR THIS)
    // For simplicity, we will temporarily use the 'transactions' table but mark it as PENDING.
    
    $baseRef = strtoupper(bin2hex(random_bytes(8)));

    $stmt = $pdo->prepare("
        INSERT INTO transactions 
          (user_id, kind, amount_cents, reference, note, status, created_at)
        VALUES 
          (?, 'debit', ?, ?, ?, 'PENDING_AUTH', NOW())
    ");
    $stmt->execute([
        $sender['id'],
        $amount_cents,
        $baseRef,
        "Transfer to {$to_acct} (PENDING AUTHORIZATION) - Note: {$note}",
    ]);
    
    $pending_tx_id = $pdo->lastInsertId();

    $pdo->commit();
    
    // REDIRECT TO THE AUTHORIZATION PAGE
    // We pass the pending transaction ID so the next page knows what to authorize
    header('Location: ' . url('transfer_authorize.php') . '?tx_id=' . $pending_tx_id);
    exit;


} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    http_response_code(500);
    echo 'Transfer validation failed: ' . htmlspecialchars($e->getMessage());
    exit;
}