<?php
include('includes/session.php');
error_reporting(0);
include('includes/dbconnection.php');

// 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();

// Cleanly handle inputs
$tabSessionID = isset($_GET['tab_id']) ? $_GET['tab_id'] : ''; 

if (!isset($_SESSION['pending_transfer']) || !isset($_POST['otp_code'])) {
    header("Location: wallet_details.php?status=error&message=Session expired.&tab_id=$tabSessionID");
    exit();
}

$student_id = $_SESSION['student_id'];
$amount = $_SESSION['pending_transfer']['amount'];
$recipient_id = $_SESSION['pending_transfer']['recipient_id'];
$recipient_acc = $_SESSION['pending_transfer']['recipient_acc'];
$input_otp = $_POST['otp_code'];
$input_pin = $_POST['transaction_pin'];

// 2. FETCH SENDER & RECEIVER DETAILS (High Performance Single Query)
$stmt = $con->prepare("
    SELECT s.studentName, s.email, w.transaction_pin, w.otp_code, w.otp_expiry, w.balance, w.account_number 
    FROM students s 
    JOIN wallets w ON s.id = w.student_id 
    WHERE s.id = ?
");
$stmt->bind_param("i", $student_id);
$stmt->execute();
$sender_data = $stmt->get_result()->fetch_assoc();

$stmt = $con->prepare("SELECT studentName, email FROM students WHERE id = ?");
$stmt->bind_param("i", $recipient_id);
$stmt->execute();
$receiver_data = $stmt->get_result()->fetch_assoc();

// 3. SECURITY VALIDATIONS
if ($input_otp !== $sender_data['otp_code'] || strtotime($sender_data['otp_expiry']) < time()) {
    die(header("Location: wallet_details.php?status=error&message=Invalid or expired OTP.&tab_id=$tabSessionID"));
}

if (!password_verify($input_pin, $sender_data['transaction_pin'])) {
    die(header("Location: wallet_details.php?status=error&message=Incorrect Transaction PIN.&tab_id=$tabSessionID"));
}

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

// 4. THE FINTECH EMAIL TEMPLATE FUNCTION
function getFintechTemplate($type, $name, $amount, $ref, $otherParty, $balance) {
    $title = ($type == 'debit') ? 'Debit Alert' : 'Credit Alert';
    $accentColor = ($type == 'debit') ? '#0f172a' : '#16a34a'; 
    $sign = ($type == 'debit') ? '-' : '+';
    
    return "
    <div style='background-color: #f8fafc; padding: 40px 10px; font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif;'>
        <div style='max-width: 500px; margin: 0 auto; background: #ffffff; border-radius: 24px; overflow: hidden; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1); border: 1px solid #e2e8f0;'>
            <div style='background: $accentColor; padding: 40px 30px; text-align: center; color: white;'>
                <p style='margin: 0; text-transform: uppercase; letter-spacing: 2px; font-size: 11px; font-weight: 800; opacity: 0.9;'>$title</p>
                <h1 style='margin: 10px 0 0; font-size: 36px; font-weight: 900;'>{$sign}â‚¦" . number_format($amount, 2) . "</h1>
            </div>
            <div style='padding: 35px;'>
                <p style='color: #64748b; font-size: 14px; margin-bottom: 5px;'>Hello <b>$name</b>,</p>
                <p style='color: #1e293b; font-size: 16px; line-height: 1.6; margin-bottom: 25px;'>
                    " . (($type == 'debit') ? "Your transfer to <b>$otherParty</b> was successful." : "Your wallet has been credited by <b>$otherParty</b>.") . "
                </p>
                
                <div style='background: #f8fafc; border: 1px solid #f1f5f9; border-radius: 20px; padding: 25px;'>
                    <table width='100%'>
                        <tr>
                            <td style='color: #94a3b8; font-size: 12px; padding-bottom: 12px;'>Transaction Ref</td>
                            <td align='right' style='color: #1e293b; font-size: 12px; font-weight: 700; padding-bottom: 12px;'>$ref</td>
                        </tr>
                        <tr>
                            <td style='color: #94a3b8; font-size: 12px; border-top: 1px solid #e2e8f0; padding-top: 12px;'>Available Balance</td>
                            <td align='right' style='color: #0f172a; font-size: 18px; font-weight: 900; border-top: 1px solid #e2e8f0; padding-top: 12px;'>â‚¦" . number_format($balance, 2) . "</td>
                        </tr>
                    </table>
                </div>

                <p style='color: #94a3b8; font-size: 11px; text-align: center; margin-top: 40px; line-height: 1.5;'>
                    This is an automated notification. For your security, never share your transaction PIN or OTP with anyone.
                </p>
            </div>
        </div>
    </div>";
}

// 5. ATOMIC TRANSACTION START
$con->begin_transaction();
try {
    $base_ref = "TRF-STD-" . strtoupper(bin2hex(random_bytes(4)));
    $ref_out = $base_ref . "-DR";
    $ref_in = $base_ref . "-CR";

    // A. Update Balances
    $con->query("UPDATE wallets SET balance = balance - $amount WHERE student_id = $student_id");
    $con->query("UPDATE wallets SET balance = balance + $amount WHERE student_id = $recipient_id");

    // B. Logs
    $stmt = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, type, reference, notes) VALUES (?, ?, ?, ?, ?)");
    
    $type_dr = 'Transfer Out (Debit)';
    $notes_dr = "Transfer to $recipient_acc ($receiver_data[studentName])";
    $stmt->bind_param("idsss", $student_id, $amount, $type_dr, $ref_out, $notes_dr);
    $stmt->execute();

    $type_cr = 'Transfer In (Deposit)';
    $notes_cr = "Transfer from $sender_data[studentName] ($sender_data[account_number])";
    $stmt->bind_param("idsss", $recipient_id, $amount, $type_cr, $ref_in, $notes_cr);
    $stmt->execute();

    // C. Clear OTP
    $con->query("UPDATE wallets SET otp_code = NULL, otp_expiry = NULL WHERE student_id = $student_id");

    $con->commit();
    $transaction_success = true;

} catch (Exception $e) {
    $con->rollback();
    die(header("Location: wallet_details.php?status=error&message=Internal error. Transaction reversed.&tab_id=$tabSessionID"));
}

// 6. FINAL EMAILS (AFTER COMMIT FOR PERFORMANCE)
if ($transaction_success) {
    // Fetch final balances for accurate reporting
    $s_bal = $con->query("SELECT balance FROM wallets WHERE student_id = $student_id")->fetch_assoc()['balance'];
    $r_bal = $con->query("SELECT balance FROM wallets WHERE student_id = $recipient_id")->fetch_assoc()['balance'];

    $mail = new PHPMailer(true);
    try {
$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');
        $mail->isHTML(true);
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64'; // ensures special characters encode correctly

        // --- Send to Sender ---
        $mail->addAddress($sender_data['email']);
        $mail->Subject = "Debit Alert: [â‚¦" . number_format($amount, 2) . "]";
        $mail->Body    = getFintechTemplate('debit', $sender_data['studentName'], $amount, $ref_out, $receiver_data['studentName'], $s_bal);
        $mail->send();

        // --- Send to Receiver ---
        $mail->clearAddresses();
        $mail->addAddress($receiver_data['email']);
        $mail->Subject = "Credit Alert: [â‚¦" . number_format($amount, 2) . "]";
        $mail->Body    = getFintechTemplate('credit', $receiver_data['studentName'], $amount, $ref_in, $sender_data['studentName'], $r_bal);
        $mail->send();

    } catch (Exception $e) {
        error_log("Mail Error: " . $mail->ErrorInfo);
    }

    unset($_SESSION['pending_transfer']);
    header("Location: wallet_details.php?status=success&message=Transaction Successful!&tab_id=$tabSessionID");
}
?>
