<?php
/**
 * init_va_transfer.php
 * Creates a pending DVA transfer record and returns the unique reference.
 * Called via AJAX when user clicks "Initiate Transfer".
 */

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

header('Content-Type: application/json');

set_exception_handler(function($e) {
    if (!headers_sent()) header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
    exit;
});

// Detect source page and start correct session
$sourcePage    = isset($_POST['source_page']) ? trim($_POST['source_page']) : '';
$tabSessionID  = isset($_POST['tab_id'])      ? trim($_POST['tab_id'])      : '';

$entrancePages = ['confirmpayen', 'confirmpaylesson', 'confirmpayen2'];
$studentPages  = ['confirmpaynd', 'confirmpaynb'];

if (in_array($sourcePage, $entrancePages)) {
    if (empty($tabSessionID)) {
        http_response_code(403);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
        exit;
    }
    session_write_close();
    session_id($tabSessionID);
    session_name('guest_portal_' . $tabSessionID);
    session_start();
} elseif (in_array($sourcePage, $studentPages)) {
    ini_set('session.gc_maxlifetime', 7200);
    ini_set('session.cookie_lifetime', 7200);
    session_name('student_portal');
    session_start();
    if (empty($tabSessionID)) {
        $tabSessionID = $_SESSION['current_tab_id'] ?? '';
    }
    if (empty($tabSessionID) || !isset($_SESSION['tabs'][$tabSessionID])) {
        http_response_code(403);
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
        exit;
    }
    $studentSession = $_SESSION['tabs'][$tabSessionID];
    $_SESSION['student_id'] = $studentSession['student_id'];
} else {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once 'vendor/autoload.php';
include('includes/dbconnection.php');
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$prefix = $_ENV['Admission_prefix'];

// Collect and sanitize inputs
$studentId   = trim($_POST['student_id']   ?? '');
$studentno   = trim($_POST['studentno']    ?? '');
$studentName = trim($_POST['studentName']  ?? '');
$email       = trim($_POST['email']        ?? '');
$feeType     = trim($_POST['fee_type']     ?? '');
$amount      = $_POST['amount']            ?? '';
$termId      = trim($_POST['term_id']      ?? '');
$sessionId   = trim($_POST['session_id']   ?? '');
$schoolType  = trim($_POST['school_type']  ?? '');
$cls         = trim($_POST['class']        ?? '');

if (!is_numeric($amount) || floatval($amount) <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid amount']);
    exit;
}

// Map source_page to payment_type
$sourceToType = [
    'confirmpayen'    => 'entrance',
    'confirmpaylesson' => 'lesson',
    'confirmpayen2'   => 'certificate',
    'confirmpaynd'    => 'new_student_day',
    'confirmpaynb'    => 'new_student_board',
];
$paymentType = $sourceToType[$sourcePage] ?? 'general';

// Generate unique reference
$transferRef = $prefix .'-'. date('dmy') .'-' . strtoupper(substr(bin2hex(random_bytes(5)), 0, 8));
$expiresAt   = date('Y-m-d H:i:s', strtotime('+30 minutes'));

// Insert into dva_pending_payments
$stmt = $con->prepare(
    "INSERT INTO dva_pending_payments
     (payment_reference, payment_type, student_id, studentno, studentName, email, fee_type, amount,
      term_id, session_id, source_page, expires_at)
     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
);
$stmt->bind_param(
    'sssssssdssss',
    $transferRef, $paymentType, $studentId, $studentno, $studentName, $email,
    $feeType, $amount, $termId, $sessionId, $sourcePage, $expiresAt
);

if (!$stmt->execute()) {
    $stmt->close();
    echo json_encode(['status' => 'error', 'message' => 'Could not create transfer reference']);
    exit;
}
$stmt->close();

echo json_encode([
    'status'             => 'success',
    'transfer_reference' => $transferRef,
    'expires_at'         => $expiresAt,
]);
