<?php
session_name('small_admin_session');
if (!is_dir(dirname(__DIR__) . '/session_data/small')) { mkdir(dirname(__DIR__) . '/session_data/small', 0700, true); } session_save_path(dirname(__DIR__) . '/session_data/small');
session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);
session_start();
error_reporting(0);
include('includes/dbconnection.php');
require_once 'includes/wallet_helpers.php';

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';
require_once 'vendor/autoload.php';

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

if (empty($_SESSION['sid'])) {
    header('location:logoutsmall.php');
    exit;
}

function redirectError(string $msg): void {
    header('Location: small_transfer_funds.php?error=' . urlencode($msg));
    exit;
}

// --- Settings check ---
if ((int)getWalletSetting($con, 'transfers_enabled', 1) === 0) {
    redirectError('Wallet transfers are currently disabled by the administrator.');
}

// --- Input ---
$from_id = filter_var($_POST['from_student_id'] ?? '', FILTER_VALIDATE_INT);
$to_id   = filter_var($_POST['to_student_id']   ?? '', FILTER_VALIDATE_INT);
$amount  = filter_var($_POST['amount']           ?? '', FILTER_VALIDATE_FLOAT);
$remark  = htmlspecialchars(trim($_POST['remark'] ?? ''));

// --- Validation ---
if (!$from_id || !$to_id) {
    redirectError('Invalid transfer participants.');
}
if ($from_id === $to_id) {
    redirectError('Sender and recipient cannot be the same student.');
}
if ($amount === false || $amount <= 0) {
    redirectError('Amount must be a positive number.');
}

// --- Fetch sender balance + email ---
$stmt = $con->prepare(
    "SELECT w.balance, s.email, s.studentName FROM wallets w JOIN students s ON w.student_id = s.id WHERE w.student_id = ?"
);
$stmt->bind_param("i", $from_id);
$stmt->execute();
$sender = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$sender) {
    redirectError('Sender wallet not found.');
}
if ((float)$sender['balance'] < $amount) {
    redirectError('Insufficient balance. Available: â‚¦' . number_format($sender['balance'], 2));
}

// --- Fetch recipient ---
$stmt2 = $con->prepare("SELECT student_id FROM wallets WHERE student_id = ?");
$stmt2->bind_param("i", $to_id);
$stmt2->execute();
$recipient = $stmt2->get_result()->fetch_assoc();
$stmt2->close();

if (!$recipient) {
    redirectError('Recipient wallet not found.');
}

// --- Fetch recipient name for email display ---
$stmt3 = $con->prepare("SELECT studentName FROM students WHERE id = ?");
$stmt3->bind_param("i", $to_id);
$stmt3->execute();
$recipientRow = $stmt3->get_result()->fetch_assoc();
$stmt3->close();
$recipientName = $recipientRow['studentName'] ?? 'Unknown';

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

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

// --- Send OTP email to sender student ---
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host       = $_ENV['SMTP_HOST'];
    $mail->SMTPAuth   = true;
    $mail->Username   = $_ENV['SMTP_NO_REPLY'];
    $mail->Password   = $_ENV['SMTP_NO_REPLY_PASSWORD'];
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = (int)$_ENV['SMTP_PORT'];
    $mail->Timeout = 10;

    $mail->setFrom($mail->Username, $_ENV['SCHOOL_NAME'] . ' Wallet Security');
    $mail->addAddress($sender['email'], $sender['studentName']);
    $mail->isHTML(true);
    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->Subject  = 'ðŸ” Authorize Wallet Transfer â€” ' . $_ENV['SCHOOL_NAME'];
    $mail->Body     = '
<!DOCTYPE html><html><head><meta charset="UTF-8"></head>
<body style="margin:0;padding:0;background:#f4f6f9;font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f6f9;padding:20px;">
<tr><td align="center">
<table width="500" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 10px 30px rgba(0,0,0,.05);">
  <tr><td style="background:#0f172a;padding:20px;text-align:center;">
    <h2 style="color:#fff;margin:0;font-size:18px;letter-spacing:1px;">' . htmlspecialchars($_ENV['SCHOOL_NAME']) . ' Wallet</h2>
  </td></tr>
  <tr><td style="padding:30px;text-align:center;">
    <h3 style="margin:0 0 10px;color:#0f172a;">Authorize Transfer</h3>
    <p style="color:#64748b;font-size:14px;margin-bottom:20px;">A transfer of <strong>&#8358;' . number_format($amount, 2) . '</strong> to <strong>' . htmlspecialchars($recipientName) . '</strong> has been initiated by an officer.</p>
    <div style="display:inline-block;background:#f1f5f9;padding:15px 30px;border-radius:12px;font-size:28px;letter-spacing:8px;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>. If you did not request this, contact the school immediately.</p>
  </td></tr>
  <tr><td style="background:#f8fafc;padding:15px;text-align:center;">
    <p style="font-size:11px;color:#94a3b8;margin:0;">&copy; ' . date('Y') . ' ' . htmlspecialchars($_ENV['SCHOOL_NAME']) . ' &bull; Secure Wallet System</p>
  </td></tr>
</table>
</td></tr></table>
</body></html>';

    $mail->send();

    // Store pending transfer ONLY after successful email
    $_SESSION['pending_officer_transfer'] = [
        'amount'          => $amount,
        'from_student_id' => $from_id,
        'to_student_id'   => $to_id,
        'remark'          => $remark,
    ];

    header('Location: small_verify_transfer_otp.php');
    exit;

} catch (Exception $e) {
    error_log('Officer transfer OTP email failed: ' . $e->getMessage());
    redirectError('Failed to send OTP email. Please try again.');
}
