<?php
// Start output buffering to prevent "headers already sent" errors
ob_start();

session_start();
require_once 'includes/auth_check.php';
require_once '../includes/email_templates.php'; // Include email templates from main includes folder

// Enable error reporting during development
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Set up a custom error log file for this script
ini_set('error_log', dirname(__FILE__) . '/transfer_errors.log');
error_log("Transfer process started for user ID: " . $_SESSION['user_id']);

$database = new Database();
$db = $database->getConnection();

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = "Invalid request.";
    header('Location: transfer.php');
    exit;
}

// Get form data
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$description = trim($_POST['description'] ?? '');
$transferMethod = $_POST['transferMethod'] ?? '';
$pin = $_POST['pin'] ?? '';
$saveBeneficiary = isset($_POST['saveBeneficiary']) ? true : false;

// Log received data (excluding sensitive info like PIN)
error_log("Transfer data received: Amount=$amount, Method=$transferMethod, Description=$description");

// Validate amount
if (!$amount || $amount <= 0) {
    $_SESSION['error_message'] = "Please enter a valid amount.";
    header('Location: transfer.php');
    exit;
}

// Validate PIN
if (strlen($pin) !== 4 || !ctype_digit($pin)) {
    $_SESSION['error_message'] = "Please enter a valid 4-digit PIN.";
    header('Location: transfer.php?step=3');
    exit;
}

// Verify PIN
try {
    $stmt = $db->prepare("SELECT pin FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user_data || !password_verify($pin, $user_data['pin'])) {
        $_SESSION['error_message'] = "Invalid PIN. Please try again.";
        header('Location: transfer.php?step=3');
        exit;
    }
} catch (PDOException $e) {
    error_log("PIN verification error: " . $e->getMessage());
    $_SESSION['error_message'] = "Error verifying PIN. Please try again.";
    header('Location: transfer.php?step=3');
    exit;
}

// Get recipient details
$recipientId = null;
$recipientName = '';
$recipientAccount = '';

try {
    if ($transferMethod === 'account') {
        $accountNumber = $_POST['accountNumber'] ?? '';
        error_log("Looking up recipient by account number: $accountNumber");
        
        $stmt = $db->prepare("SELECT id, first_name, last_name, account_number, email FROM users WHERE account_number = ? AND id != ? AND status = 'active'");
        $stmt->execute([$accountNumber, $_SESSION['user_id']]);
        $recipient = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$recipient) {
            error_log("Recipient account not found: $accountNumber");
            $_SESSION['error_message'] = "Recipient account not found or is inactive.";
            header('Location: transfer.php?step=2');
            exit;
        }
        
        $recipientId = $recipient['id'];
        $recipientName = $recipient['first_name'] . ' ' . $recipient['last_name'];
        $recipientAccount = $recipient['account_number'];
        $recipientEmail = $recipient['email'];
        
        error_log("Recipient found: ID=$recipientId, Name=$recipientName");
    } elseif ($transferMethod === 'beneficiary') {
        $beneficiaryId = $_POST['beneficiaryId'] ?? '';
        error_log("Looking up recipient by beneficiary ID: $beneficiaryId");
        
        $stmt = $db->prepare("
            SELECT u.id, u.first_name, u.last_name, u.account_number, u.email 
            FROM users u 
            JOIN beneficiaries b ON u.id = b.recipient_id 
            WHERE b.id = ? AND b.user_id = ?
        ");
        $stmt->execute([$beneficiaryId, $_SESSION['user_id']]);
        $recipient = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$recipient) {
            error_log("Beneficiary not found: $beneficiaryId");
            $_SESSION['error_message'] = "Beneficiary not found.";
            header('Location: transfer.php?step=2');
            exit;
        }
        
        $recipientId = $recipient['id'];
        $recipientName = $recipient['first_name'] . ' ' . $recipient['last_name'];
        $recipientAccount = $recipient['account_number'];
        $recipientEmail = $recipient['email'];
        
        error_log("Recipient found: ID=$recipientId, Name=$recipientName");
    } else {
        error_log("Invalid transfer method: $transferMethod");
        $_SESSION['error_message'] = "Invalid transfer method.";
        header('Location: transfer.php?step=2');
        exit;
    }
} catch (PDOException $e) {
    error_log("Error getting recipient details: " . $e->getMessage());
    $_SESSION['error_message'] = "Error retrieving recipient details. Please try again.";
    header('Location: transfer.php?step=2');
    exit;
}

// Check if user has sufficient balance from account_balances table
try {
    error_log("Checking sender balance for user ID: " . $_SESSION['user_id']);
    
    // Now get the balance
    $stmt = $db->prepare("
        SELECT ab.balance, u.currency, u.first_name, u.last_name, u.email 
        FROM account_balances ab
        JOIN users u ON ab.user_id = u.id
        WHERE ab.user_id = ?
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $sender = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$sender) {
        error_log("No balance record found for user ID: " . $_SESSION['user_id']);
        $_SESSION['error_message'] = "Could not retrieve your account balance.";
        header('Location: transfer.php?step=1');
        exit;
    }
    
    error_log("Sender balance: " . $sender['balance'] . ", Transfer amount: " . $amount);
    
    if ($sender['balance'] < $amount) {
        error_log("Insufficient funds: Balance=" . $sender['balance'] . ", Amount=$amount");
        $_SESSION['error_message'] = "Insufficient funds. Your current balance is " . $sender['currency'] . " " . number_format($sender['balance'], 2);
        header('Location: transfer.php?step=1');
        exit;
    }
} catch (PDOException $e) {
    error_log("Error checking balance: " . $e->getMessage());
    $_SESSION['error_message'] = "Error checking your account balance. Please try again.";
    header('Location: transfer.php?step=1');
    exit;
}

try {
    // Begin transaction
    error_log("Starting database transaction");
    $db->beginTransaction();
    
    // Generate transaction IDs with unique suffixes for sender and recipient
    $baseTransactionId = 'TRF' . time() . rand(1000, 9999);
    $senderTransactionId = $baseTransactionId . 'S'; // Add 'S' for sender
    $recipientTransactionId = $baseTransactionId . 'R'; // Add 'R' for recipient
    
    error_log("Generated transaction IDs: Sender=$senderTransactionId, Recipient=$recipientTransactionId");
    
    // Deduct amount from sender in account_balances table
    error_log("Updating sender balance: -$amount");
    $stmt = $db->prepare("UPDATE account_balances SET balance = balance - ? WHERE user_id = ?");
    $stmt->execute([$amount, $_SESSION['user_id']]);
    $rowsAffected = $stmt->rowCount();
    error_log("Sender balance update affected $rowsAffected rows");
    
    // Check if recipient has an account balance record
    error_log("Checking if recipient has a balance record");
    $stmt = $db->prepare("SELECT COUNT(*) as count FROM account_balances WHERE user_id = ?");
    $stmt->execute([$recipientId]);
    $hasBalance = $stmt->fetch(PDO::FETCH_ASSOC)['count'] > 0;
    
    if ($hasBalance) {
        // Update existing balance
        error_log("Updating recipient balance: +$amount");
        $stmt = $db->prepare("UPDATE account_balances SET balance = balance + ? WHERE user_id = ?");
        $stmt->execute([$amount, $recipientId]);
        $rowsAffected = $stmt->rowCount();
        error_log("Recipient balance update affected $rowsAffected rows");
    } else {
        // Create new balance record
        error_log("Creating new balance record for recipient: $amount");
        $stmt = $db->prepare("INSERT INTO account_balances (user_id, balance) VALUES (?, ?)");
        $stmt->execute([$recipientId, $amount]);
        $rowsAffected = $stmt->rowCount();
        error_log("New balance record creation affected $rowsAffected rows");
    }
    
    // Record transaction for sender (debit)
    error_log("Recording sender transaction");
    $stmt = $db->prepare("
        INSERT INTO transactions 
        (user_id, transaction_type, amount, description, reference, recipient_id, status) 
        VALUES (?, 'transfer', ?, ?, ?, ?, 'completed')
    ");
    $stmt->execute([
        $_SESSION['user_id'],
        -$amount, // Negative amount for sender
        $description,
        $senderTransactionId, // Use sender-specific transaction ID
        $recipientId
    ]);
    
    // Record transaction for recipient (credit)
    error_log("Recording recipient transaction");
    $stmt = $db->prepare("
        INSERT INTO transactions 
        (user_id, transaction_type, amount, description, reference, status) 
        VALUES (?, 'transfer', ?, ?, ?, 'completed')
    ");
    $stmt->execute([
        $recipientId,
        $amount, // Positive amount for recipient
        $description,
        $recipientTransactionId // Use recipient-specific transaction ID
    ]);
    
    // Save as beneficiary if requested
    if ($saveBeneficiary && $transferMethod === 'account') {
        error_log("Saving recipient as beneficiary");
        $stmt = $db->prepare("
            INSERT INTO beneficiaries (user_id, recipient_id, name, account_number) 
            VALUES (?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE updated_at = NOW()
        ");
        $stmt->execute([
            $_SESSION['user_id'],
            $recipientId,
            $recipientName,
            $recipientAccount
        ]);
    }
    
    // Commit transaction
    error_log("Committing database transaction");
    $db->commit();
    
    // Send email notification to sender
    error_log("Sending email notification");
    $senderName = $sender['first_name'] . ' ' . $sender['last_name'];
    try {
        sendTransferEmail(
            $sender['email'],
            $senderName,
            $recipientName,
            $amount,
            $sender['currency'],
            $recipientAccount,
            $senderTransactionId, // Use sender's transaction ID for the email
            $description
        );
        error_log("Email sent successfully");
    } catch (Exception $e) {
        error_log("Email sending failed: " . $e->getMessage());
        // Continue even if email fails
    }
    
    // Clear transfer session data
    unset($_SESSION['transfer_data']);

   // Redirect to transfer success page with transaction ID
error_log("Transfer completed successfully, redirecting to transfer_success.php");
header('Location: transfer_success.php?id=' . $senderTransactionId);
ob_end_flush(); // Flush the output buffer and send the response
exit;

    
} catch (PDOException $e) {
    // Rollback transaction on error
    error_log("Transfer error, rolling back transaction: " . $e->getMessage());
    $db->rollBack();
    
    $_SESSION['error_message'] = "An error occurred while processing your transfer: " . $e->getMessage();
    header('Location: transfer.php');
    ob_end_flush(); // Flush the output buffer and send the response
    exit;
} catch (Exception $e) {
    // Handle any other exceptions
    error_log("Unexpected error: " . $e->getMessage());
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    
    $_SESSION['error_message'] = "An unexpected error occurred: " . $e->getMessage();
    header('Location: transfer.php');
    ob_end_flush(); // Flush the output buffer and send the response
    exit;
}

// End output buffering and send the response
ob_end_flush();
?>
