<?php
include('includes/session.php');
error_reporting(E_ALL);
include('includes/dbconnection.php');
require_once 'includes/wallet_helpers.php';

// Block transfer if disabled by admin
if ((int)getWalletSetting($con, 'transfers_enabled', 1) === 0) {
    header('Location: wallet_details.php?status=error&message=' . urlencode('Wallet transfers are currently disabled by the administrator.'));
    exit;
}

// Include PHPMailer and QR code libraries
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use Dotenv\Dotenv;

require 'phpmailer/src/Exception.php';
require 'phpmailer/src/PHPMailer.php';
require 'phpmailer/src/SMTP.php';


// Load Composer dependencies
require_once 'vendor/autoload.php';
// Load environment variables
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

$student_id = $_SESSION['student_id'];
$recipient_acc = $_POST['recipient_acc'];
$amount = floatval($_POST['amount']);
$tabSessionID = $_GET['tab_id']; // Tab ID


// 1. Basic Validation
if ($amount <= 100) {
    die(header("Location: wallet_details.php?status=error&message=Minimum transfer is â‚¦100.&tab_id=$tabSessionID"));
}

// 2. Check Sender Balance & Recipient Existence (Atomic Check)
$stmt = $con->prepare("SELECT w.balance, s.email FROM wallets w JOIN students s ON w.student_id = s.id WHERE w.student_id = ?");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$sender = $stmt->get_result()->fetch_assoc();

if ($sender['balance'] < $amount) {
    die(header("Location: wallet_details.php?status=error&message=Insufficient balance.&tab_id=$tabSessionID"));
}

$stmt = $con->prepare("SELECT student_id FROM wallets WHERE account_number = ? AND student_id != ?");
$stmt->bind_param("si", $recipient_acc, $student_id);
$stmt->execute();
$recipient = $stmt->get_result()->fetch_assoc();

if (!$recipient) {
    die(header("Location: wallet_details.php?status=error&message=Recipient account not found.&tab_id=$tabSessionID"));
}

// 3. Generate OTP (Security Control)
$otp = rand(100000, 999999);
$expiry = date("Y-m-d H:i:s", strtotime("+10 minutes"));

$stmt = $con->prepare("UPDATE wallets SET otp_code = ?, otp_expiry = ? WHERE student_id = ?");
$stmt->bind_param("ssi", $otp, $expiry, $student_id);
$stmt->execute();

// 4. Send Email via PHPMailer (Using your .env credentials)
$mail = new PHPMailer(true);
try {
    // Standard SMTP setup using your existing includes/env variables
$mail->isSMTP();
$mail->Host = $_ENV['SMTP_HOST'];
$mail->SMTPAuth = true;
$mail->Username = $_ENV['SMTP_USERNAME'];
$mail->Password = $_ENV['SMTP_PASSWORD'];
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = $_ENV['SMTP_PORT'];
$mail->Timeout = 10;

// Set sender info
$mail->setFrom($_ENV['SMTP_USERNAME'], $_ENV['SCHOOL_NAME'] . ' Wallet Security');

// Recipient
$mail->addAddress($sender['email']);

// HTML email setup
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64'; // ensures special characters encode correctly
$mail->Subject = "ðŸ” Confirm Your Transfer";

// Email body (modern, premium, UTF-8 safe)
$mail->Body = '
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Authorize Transfer</title>
</head>
<body style="margin:0; padding:0; background-color:#f4f6f9; font-family:Arial, sans-serif;">

<table width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f6f9; padding:20px;">
<tr>
<td align="center">

    <!-- Main Container -->
    <table width="100%" max-width="500px" cellpadding="0" cellspacing="0" style="background:#ffffff; border-radius:16px; overflow:hidden; box-shadow:0 10px 30px rgba(0,0,0,0.05);">

        <!-- Header -->
        <tr>
            <td style="background:#0f172a; padding:20px; text-align:center;">
                <h2 style="color:#ffffff; margin:0; font-size:18px; letter-spacing:1px;">
                    '.$_ENV['SCHOOL_NAME'].' Wallet
                </h2>
            </td>
        </tr>

        <!-- Body -->
        <tr>
            <td style="padding:30px; text-align:center;">
                <h3 style="margin:0 0 10px; color:#0f172a;">Authorize Your Transfer</h3>
                <p style="color:#64748b; font-size:14px; margin-bottom:25px;">
                    You are about to transfer
                </p>

                <!-- Amount -->
                <div style="font-size:28px; font-weight:bold; color:#0f172a; margin-bottom:20px;">
                    &#8358;'.number_format($amount, 2).'
                </div>

                <!-- OTP Box -->
                <div style="
                    display:inline-block;
                    background:#f1f5f9;
                    padding:15px 25px;
                    border-radius:12px;
                    font-size:24px;
                    letter-spacing:6px;
                    font-weight:bold;
                    color:#0f172a;
                    margin-bottom:20px;
                ">
                    '.$otp.'
                </div>

                <p style="color:#64748b; font-size:13px;">
                    This code expires in <b>10 minutes</b>.
                </p>
            </td>
        </tr>

        <!-- Divider -->
        <tr>
            <td style="padding:0 30px;">
                <hr style="border:none; border-top:1px solid #e2e8f0;">
            </td>
        </tr>

        <!-- Security Notice -->
        <tr>
            <td style="padding:20px 30px; text-align:center;">
                <p style="font-size:12px; color:#94a3b8; line-height:1.6;">
                    âš ï¸ Never share this code with anyone. Our team will never ask for your OTP.
                </p>
            </td>
        </tr>

        <!-- Footer -->
        <tr>
            <td style="background:#f8fafc; padding:15px; text-align:center;">
                <p style="font-size:11px; color:#94a3b8; margin:0;">
                    Â© '.date("Y").' '.$_ENV['SCHOOL_NAME'].' â€¢ Secure Wallet System
                </p>
            </td>
        </tr>

    </table>

</td>
</tr>
</table>

</body>
</html>
';
    $mail->send();
    
    // Store transfer data in session for the final step
    $_SESSION['pending_transfer'] = [
        'amount' => $amount,
        'recipient_acc' => $recipient_acc,
        'recipient_id' => $recipient['student_id']
    ];

    header("Location: verify_transfer.php?tab_id=$tabSessionID"); // Create this small UI page next
} catch (Exception $e) {
    header("Location: wallet_details.php?status=error&message=Email failed to send.&tab_id=$tabSessionID");
}
?>
