<?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');

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;
}

if (!isset($_SESSION['pending_officer_transfer'])) {
    header('Location: small_transfer_funds.php?error=' . urlencode('Session expired. Please start the transfer again.'));
    exit;
}

if (!isset($_POST['otp_code'])) {
    header('Location: small_transfer_funds.php?error=' . urlencode('Invalid request.'));
    exit;
}

$pending   = $_SESSION['pending_officer_transfer'];
$from_id   = (int)$pending['from_student_id'];
$to_id     = (int)$pending['to_student_id'];
$amount    = (float)$pending['amount'];
$remark    = $pending['remark'] ?? '';
$input_otp = trim($_POST['otp_code']);

// --- Fetch sender data ---
$stmt = $con->prepare(
    "SELECT s.studentName, s.email, 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", $from_id);
$stmt->execute();
$sender = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$sender) {
    header('Location: small_transfer_funds.php?error=' . urlencode('Sender not found.'));
    exit;
}

// --- Fetch recipient data ---
$stmt2 = $con->prepare("SELECT studentName, email FROM students WHERE id = ?");
$stmt2->bind_param("i", $to_id);
$stmt2->execute();
$receiver = $stmt2->get_result()->fetch_assoc();
$stmt2->close();

if (!$receiver) {
    header('Location: small_transfer_funds.php?error=' . urlencode('Recipient not found.'));
    exit;
}

// --- OTP Validation (no PIN check) ---
if ($input_otp !== (string)$sender['otp_code'] || strtotime($sender['otp_expiry']) < time()) {
    header('Location: small_verify_transfer_otp.php?error=' . urlencode('Invalid or expired OTP. Please try again.'));
    exit;
}

if ((float)$sender['balance'] < $amount) {
    header('Location: small_transfer_funds.php?error=' . urlencode('Insufficient balance.'));
    exit;
}

// --- Email template helper ---
function getOfficerTransferEmailTemplate(string $type, string $name, float $amount, string $ref, string $otherParty, float $balance): string
{
    $title       = ($type === 'debit') ? 'Debit Alert' : 'Credit Alert';
    $accentColor = ($type === 'debit') ? '#0f172a' : '#16a34a';
    $sign        = ($type === 'debit') ? '-' : '+';
    $action      = ($type === 'debit')
        ? "Your wallet was debited for a transfer to <b>{$otherParty}</b>."
        : "Your wallet has been credited from <b>{$otherParty}</b>.";

    return "
    <div style='background:#f8fafc;padding:40px 10px;font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Roboto,Arial,sans-serif;'>
      <div style='max-width:500px;margin:0 auto;background:#fff;border-radius:24px;overflow:hidden;box-shadow:0 10px 15px -3px rgba(0,0,0,.1);border:1px solid #e2e8f0;'>
        <div style='background:{$accentColor};padding:40px 30px;text-align:center;color:#fff;'>
          <p style='margin:0;text-transform:uppercase;letter-spacing:2px;font-size:11px;font-weight:800;opacity:.9;'>{$title}</p>
          <h1 style='margin:10px 0 0;font-size:36px;font-weight:900;'>{$sign}&#8358;" . 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;'>{$action}</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;'>&#8358;" . number_format($balance, 2) . "</td>
              </tr>
            </table>
          </div>
          <p style='color:#94a3b8;font-size:11px;text-align:center;margin-top:30px;'>This is an automated notification from the school wallet system.</p>
        </div>
      </div>
    </div>";
}

// --- Atomic Transaction ---
$base_ref = 'TRF-OFF-' . strtoupper(bin2hex(random_bytes(4)));
$ref_out  = $base_ref . '-DR';
$ref_in   = $base_ref . '-CR';

$con->begin_transaction();
try {
    // 1. Debit sender
    $s1 = $con->prepare("UPDATE wallets SET balance = balance - ? WHERE student_id = ? AND balance >= ?");
    $s1->bind_param("did", $amount, $from_id, $amount);
    $s1->execute();
    if ($s1->affected_rows !== 1) throw new Exception("Wallet deduction failed â€” insufficient balance.");
    $s1->close();

    // 2. Credit recipient
    $s2 = $con->prepare("UPDATE wallets SET balance = balance + ? WHERE student_id = ?");
    $s2->bind_param("di", $amount, $to_id);
    $s2->execute();
    $s2->close();

    // 3. Log debit
    $note_out = "Officer transfer to {$receiver['studentName']}. {$remark}";
    $type_out = 'Transfer Out';
    $s3 = $con->prepare(
        "INSERT INTO wallet_transactions (student_id, amount, type, status, reference, notes, created_at)
         VALUES (?, ?, ?, 'success', ?, ?, NOW())"
    );
    $s3->bind_param("idsss", $from_id, $amount, $type_out, $ref_out, $note_out);
    $s3->execute();
    $s3->close();

    // 4. Log credit
    $note_in = "Officer transfer from {$sender['studentName']}. {$remark}";
    $type_in = 'Transfer In';
    $s4 = $con->prepare(
        "INSERT INTO wallet_transactions (student_id, amount, type, status, reference, notes, created_at)
         VALUES (?, ?, ?, 'success', ?, ?, NOW())"
    );
    $s4->bind_param("idsss", $to_id, $amount, $type_in, $ref_in, $note_in);
    $s4->execute();
    $s4->close();

    // 5. Clear OTP
    $s5 = $con->prepare("UPDATE wallets SET otp_code = NULL, otp_expiry = NULL WHERE student_id = ?");
    $s5->bind_param("i", $from_id);
    $s5->execute();
    $s5->close();

    $con->commit();

} catch (Exception $e) {
    $con->rollback();
    header('Location: small_transfer_funds.php?error=' . urlencode('Transaction failed: ' . $e->getMessage()));
    exit;
}

// --- Post-commit: fetch final balances for emails ---
$s_bal_res = $con->query("SELECT balance FROM wallets WHERE student_id = {$from_id}");
$s_bal     = (float)($s_bal_res->fetch_assoc()['balance'] ?? 0);

$r_bal_res = $con->query("SELECT balance FROM wallets WHERE student_id = {$to_id}");
$r_bal     = (float)($r_bal_res->fetch_assoc()['balance'] ?? 0);

// --- Send emails (non-fatal) ---
try {
    $mail = new PHPMailer(true);
    $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');
    $mail->isHTML(true);
    $mail->CharSet  = 'UTF-8';
    $mail->Encoding = 'base64';

    // Debit alert to sender
    $mail->addAddress($sender['email'], $sender['studentName']);
    $mail->Subject = 'Debit Alert: [â‚¦' . number_format($amount, 2) . ']';
    $mail->Body    = getOfficerTransferEmailTemplate('debit', $sender['studentName'], $amount, $ref_out, $receiver['studentName'], $s_bal);
    $mail->send();

    // Credit alert to recipient
    $mail->clearAddresses();
    $mail->addAddress($receiver['email'], $receiver['studentName']);
    $mail->Subject = 'Credit Alert: [â‚¦' . number_format($amount, 2) . ']';
    $mail->Body    = getOfficerTransferEmailTemplate('credit', $receiver['studentName'], $amount, $ref_in, $sender['studentName'], $r_bal);
    $mail->send();

} catch (Exception $mailEx) {
    error_log('Officer transfer email failed: ' . $mailEx->getMessage());
}

// --- Cleanup and redirect ---
unset($_SESSION['pending_officer_transfer']);
header('Location: small_transfer_funds.php?status=success&ref=' . urlencode($base_ref));
exit;
