<?php
session_start();
require_once 'includes/auth_check.php';

// Security checks
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
    $_SESSION['error_message'] = 'Unauthorized access.';
    header('Location: international-transfer.php');
    exit;
}

require_once '../config/database.php';
require_once '../includes/functions.php';

// Get and validate inputs
$sender_id = $_SESSION['user_id'];
$pin = $_POST['pin'] ?? '';
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$currency = $_POST['currency'] ?? '';
$fee = filter_input(INPUT_POST, 'fee', FILTER_VALIDATE_FLOAT);
$description = trim($_POST['description'] ?? '');
$recipient_name = trim($_POST['recipient_name'] ?? '');
$bank_name = trim($_POST['bank_name'] ?? '');
$swift_code = trim($_POST['swift_code'] ?? '');
$account_number = trim($_POST['account_number'] ?? '');
$address = trim($_POST['address'] ?? '');
$country = trim($_POST['country'] ?? '');

// Validate required fields
if (!$amount || $amount <= 0 || !$fee || empty($currency) || empty($recipient_name) || empty($bank_name) || empty($swift_code) || empty($account_number) || empty($country)) {
    $_SESSION['error_message'] = 'All required fields must be provided.';
    header('Location: international-transfer.php?step=3');
    exit;
}
if (strlen($pin) !== 4) {
    $_SESSION['error_message'] = 'Please enter your 4-digit PIN.';
    header('Location: international-transfer.php?step=3');
    exit;
}

$database = new Database();
$db = $database->getConnection();
$transfer_success = false;
$transfer_error = null;

try {
    // Verify PIN
    $user_stmt = $db->prepare("SELECT pin FROM users WHERE id = ?");
    $user_stmt->execute([$sender_id]);
    $sender_user = $user_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sender_user || !password_verify($pin, $sender_user['pin'])) {
        throw new Exception('Incorrect PIN. Please try again.');
    }

    // Get sender's balance
    $balance_stmt = $db->prepare("SELECT * FROM account_balances WHERE user_id = ?");
    $balance_stmt->execute([$sender_id]);
    $sender_balance = $balance_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$sender_balance) { throw new Exception("Could not retrieve account balance."); }

    // Calculate total amount
    $total_amount = $amount + $fee;
    $exchange_rate = 1;
    if ($currency !== $sender_balance['currency']) {
        $rates = ['USD' => 1.00, 'EUR' => 0.85, 'GBP' => 0.73, 'JPY' => 110.25, 'CAD' => 1.25, 'AUD' => 1.35, 'CHF' => 0.92, 'CNY' => 6.45, 'INR' => 74.50, 'SGD' => 1.35];
        $exchange_rate = $rates[$sender_balance['currency']] / $rates[$currency];
        $total_amount_in_user_currency = $total_amount * $exchange_rate;
    } else {
        $total_amount_in_user_currency = $total_amount;
    }

    if ($sender_balance['balance'] < $total_amount_in_user_currency) {
        throw new Exception("You have insufficient funds to complete this wire transfer.");
    }

    // Begin transaction
    $db->beginTransaction();
    $db->prepare("UPDATE account_balances SET balance = balance - ? WHERE user_id = ?")->execute([$total_amount_in_user_currency, $sender_id]);
    $reference = 'WIRE_' . time() . '_' . rand(1000, 9999);
    $wire_stmt = $db->prepare("INSERT INTO wire_transfers (user_id, recipient_name, bank_name, swift_code, account_number, bank_address, country, amount, fee, currency, description, reference, status, exchange_rate, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, NOW())");
    $wire_stmt->execute([$sender_id, $recipient_name, $bank_name, $swift_code, $account_number, $address, $country, $amount, $fee, $currency, $description, $reference, $exchange_rate]);
    $wire_transfer_id = $db->lastInsertId();
    $transaction_stmt = $db->prepare("INSERT INTO transactions (user_id, type, amount, currency, description, reference, status, transaction_type) VALUES (?, 'debit', ?, ?, ?, ?, 'pending', 'wire_transfer')");
    $transaction_stmt->execute([$sender_id, $total_amount_in_user_currency, $sender_balance['currency'], $description ?: "Wire transfer to " . $recipient_name, $reference . '_D']);
    $db->commit();
    
    unset($_SESSION['wire_transfer_data']);
    $_SESSION['wire_transfer_success'] = ['id' => $wire_transfer_id, 'reference' => $reference, 'amount' => $amount, 'fee' => $fee, 'currency' => $currency, 'recipient_name' => $recipient_name, 'bank_name' => $bank_name];
    $transfer_success = true;
    
    // Get user details for direct email
    $user_stmt = $db->prepare("SELECT first_name, last_name, email FROM users WHERE id = ?");
    $user_stmt->execute([$sender_id]);
    $user = $user_stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($user && !empty($user['email'])) {
        $userName = trim($user['first_name'] . ' ' . $user['last_name']);
        
        // Direct email implementation
        $to = $user['email'];
        $subject = "Wire Transfer Confirmation - " . $reference;
        $message = "
        <html>
        <head>
        <title>Wire Transfer Confirmation</title>
        <style>
        body {font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 0; background-color: #f4f4f4;}
        .container {max-width: 600px; margin: 0 auto; background-color: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 0 10px rgba(0,0,0,0.1);}
        .header {background-color: #2563eb; color: white; padding: 20px; text-align: center;}
        .content {padding: 20px;}
        .details {background-color: #f9f9f9; padding: 15px; margin: 15px 0; border-radius: 5px;}
        .row {margin-bottom: 10px; border-bottom: 1px solid #eee; padding-bottom: 10px; display: flex; justify-content: space-between;}
        .footer {background-color: #f8f9fa; padding: 15px; text-align: center; font-size: 12px; color: #6c757d;}
        .amount {font-size: 24px; font-weight: bold; color: #2563eb; text-align: center; margin: 20px 0;}
        </style>
        </head>
        <body>
        <div class='container'>
            <div class='header'>
                <h2>Wire Transfer Confirmation</h2>
            </div>
            
            <div class='content'>
                <p>Dear " . htmlspecialchars($userName) . ",</p>
                
                <p>Your wire transfer has been initiated successfully with reference number: <strong>" . htmlspecialchars($reference) . "</strong></p>
                
                <div class='amount'>" . htmlspecialchars($currency) . " " . number_format($amount, 2) . "</div>
                
                <div class='details'>
                    <div class='row'>
                        <span><strong>Amount:</strong></span>
                        <span>" . htmlspecialchars($currency) . " " . number_format($amount, 2) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Fee:</strong></span>
                        <span>" . htmlspecialchars($currency) . " " . number_format($fee, 2) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Total Debited:</strong></span>
                        <span>" . htmlspecialchars($currency) . " " . number_format($amount + $fee, 2) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Recipient:</strong></span>
                        <span>" . htmlspecialchars($recipient_name) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Bank:</strong></span>
                        <span>" . htmlspecialchars($bank_name) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>SWIFT Code:</strong></span>
                        <span>" . htmlspecialchars($swift_code) . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Account Number:</strong></span>
                        <span>" . htmlspecialchars(substr($account_number, 0, -4) . '****') . "</span>
                    </div>
                    <div class='row'>
                        <span><strong>Country:</strong></span>
                        <span>" . htmlspecialchars($country) . "</span>
                    </div>
                    " . (!empty($description) ? "
                    <div class='row' style='border-bottom: none;'>
                        <span><strong>Description:</strong></span>
                        <span>" . htmlspecialchars($description) . "</span>
                    </div>" : "") . "
                </div>
                
                <p>Your transfer is being processed and will typically take 1-5 business days to complete. You will receive a notification when the transfer is complete.</p>
                
                <p>If you have any questions about this transaction, please contact our customer support team and reference the transaction ID provided above.</p>
                
                <p>Thank you for banking with us.</p>
                
                <p>Best regards,<br>Banking Team</p>
            </div>
            
            <div class='footer'>
                <p>This is an automated message. Please do not reply to this email.</p>
                <p>If you did not initiate this transaction, please contact us immediately.</p>
            </div>
        </div>
        <!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
        </html>
        ";

        // Set content-type header for sending HTML email
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
        $headers .= "From: First National Bank Incorporated <noreply@" . $_SERVER['HTTP_HOST'] . ">" . "\r\n";

        // Send email directly
        $direct_mail_result = mail($to, $subject, $message, $headers);
        error_log("Direct mail result: " . ($direct_mail_result ? "SUCCESS" : "FAILED"));

        // If direct mail fails, try an alternative approach
        if (!$direct_mail_result) {
            // Try with minimal headers
            $simple_headers = "From: noreply@" . $_SERVER['HTTP_HOST'] . "\r\n" .
                             "Content-Type: text/html; charset=UTF-8\r\n";
            
            $simple_mail_result = mail($to, $subject, $message, $simple_headers);
            error_log("Simple mail result: " . ($simple_mail_result ? "SUCCESS" : "FAILED"));
        }
    } else {
        error_log("Could not send email: User not found or email is empty");
    }
    
    // Now try the original email method as a backup
    try {
        error_log("Starting original email notification process for wire transfer: " . $reference);
        
        // Check if email_templates.php exists
        $email_template_path = '../includes/email_templates.php';
        if (file_exists($email_template_path)) {
            require_once $email_template_path;
            
            // Check if function exists
            if (function_exists('sendWireTransferEmail')) {
                error_log("Attempting to send wire transfer email using template function");
                
                $emailResult = sendWireTransferEmail(
                    $user['email'],
                    $userName,
                    $amount,
                    $currency,
                    $fee,
                    $recipient_name,
                    $bank_name,
                    $swift_code,
                    $account_number,
                    $reference,
                    $description,
                    $country
                );
                
                if ($emailResult) {
                    error_log("Template wire transfer email sent successfully");
                } else {
                    error_log("Template wire transfer email failed to send");
                }
            } else {
                error_log("sendWireTransferEmail function not found in template file");
            }
        } else {
            error_log("Email templates file not found at: " . $email_template_path);
        }
    } catch (Exception $e) {
        error_log("Original email method error: " . $e->getMessage());
    }
    
} catch (Exception $e) {
    if ($db->inTransaction()) { $db->rollBack(); }
    error_log("Wire Transfer Error: " . $e->getMessage());
    $_SESSION['error_message'] = $e->getMessage();
    header('Location: international-transfer.php?step=3');
    exit;
}

// Show the animation page with a meta refresh to guarantee the redirect
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Processing Wire Transfer</title>
    <!-- Meta refresh to guarantee redirect after 10 seconds -->
    <meta http-equiv="refresh" content="10;url=wire-transfer-success.php">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .processing-container {
            max-width: 600px;
            margin: 100px auto;
            text-align: center;
            padding: 2rem;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
        }
        .progress {
            height: 20px;
            margin: 2rem 0;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-bar {
            background-color: #2563eb;
            animation: progressAnimation 10s linear forwards;
        }
        @keyframes progressAnimation {
            0% { width: 0%; }
            100% { width: 100%; }
        }
        .processing-steps {
            max-width: 400px;
            margin: 0 auto;
            text-align: left;
        }
        .processing-step {
            display: flex;
            align-items: center;
            margin-bottom: 1rem;
            padding: 0.5rem;
            border-radius: 0.5rem;
            opacity: 0.5;
        }
        .step-icon {
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 1rem;
            background-color: #e9ecef;
            color: #6c757d;
        }
        .step-1 { animation: activateStep 0.5s forwards 0.5s; }
        .step-2 { animation: activateStep 0.5s forwards 2s; }
        .step-3 { animation: activateStep 0.5s forwards 4s; }
        .step-4 { animation: activateStep 0.5s forwards 6s; }
        .step-5 { animation: activateStep 0.5s forwards 8s; }
        .step-6 { animation: activateStep 0.5s forwards 9s; }
        
        @keyframes activateStep {
            to {
                opacity: 1;
                background-color: rgba(37, 99, 235, 0.1);
            }
        }
        .step-1 .step-icon { animation: completeStep 0.5s forwards 2s; }
        .step-2 .step-icon { animation: completeStep 0.5s forwards 4s; }
        .step-3 .step-icon { animation: completeStep 0.5s forwards 6s; }
        .step-4 .step-icon { animation: completeStep 0.5s forwards 8s; }
        .step-5 .step-icon { animation: completeStep 0.5s forwards 9s; }
        .step-6 .step-icon { animation: completeStep 0.5s forwards 9.5s; }
        
        @keyframes completeStep {
            to {
                background-color: #10b981;
                color: white;
            }
        }
    </style>
</head>
<body>
    <div class="processing-container">
        <h3>Processing Your Wire Transfer</h3>
        <p class="text-muted">Please wait while we process your transaction</p>
        
        <div class="progress">
            <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"></div>
        </div>
        
        <div class="processing-steps">
            <div class="processing-step step-1">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Initializing transaction...</div>
            </div>
            <div class="processing-step step-2">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Validating transaction details...</div>
            </div>
            <div class="processing-step step-3">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Processing secure payment...</div>
            </div>
            <div class="processing-step step-4">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Verifying recipient information...</div>
            </div>
            <div class="processing-step step-5">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Preparing for bank approval...</div>
            </div>
            <div class="processing-step step-6">
                <div class="step-icon"><i class='bx bx-check-circle'></i></div>
                <div class="step-text">Finalizing transaction...</div>
            </div>
        </div>
        
        <p class="mt-4">You will be redirected automatically...</p>
    </div>
<!--Start of Tawk.to Script-->
<script type="text/javascript">
var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
(function(){
var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
s1.async=true;
s1.src='https://embed.tawk.to/698919832510d91c3c5b9ece/1jgvonb1o';
s1.charset='UTF-8';
s1.setAttribute('crossorigin','*');
s0.parentNode.insertBefore(s1,s0);
})();
</script>
<!--End of Tawk.to Script-->
</body>
</html>
