<?php
include('includes/dbconnection.php');
require_once __DIR__ . '/includes/session_term_helper.php';
require_once 'vendor/autoload.php';

$stResult = resolveCurrentSessionTerm($con);
$currentSessionId = $stResult['session_id'];
$currentSessionName = $stResult['session_name'];
$currentTermId = $stResult['term_id'];
$currentTermName = $stResult['term_name'];

// === Load .env secrets ===
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$paystackSecret = $_ENV['PAYSTACK_SECRET_KEY'];

// === Get the raw POST data ===
$input = @file_get_contents("php://input");
$event = json_decode($input, true);

// === Signature verification ===
$signature = $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] ?? '';
if (!$paystackSecret || $signature !== hash_hmac('sha512', $input, $paystackSecret)) {
    http_response_code(400);
    exit('Invalid signature');
}

// === Handle Successful Charges ===
if (($event['event'] ?? '') === 'charge.success') {
    $data = $event['data'];
    $email = $data['customer']['email'] ?? '';
    $amount = $data['amount'] / 100;
    $reference = $data['reference'];

    // ==========================================================
// CASE A: WALLET DEPOSIT (Email has a + tagging)
// ==========================================================
    if (strpos($email, '+') !== false) {

        preg_match('/\+(.*?)@/', $email, $matches);
        $student_id = isset($matches[1]) ? (int) $matches[1] : 0;

        if ($student_id > 0) {
            // 1. Check if this reference has already been processed
            $refCheck = $con->prepare("SELECT id FROM wallet_transactions WHERE reference = ?");
            $refCheck->bind_param("s", $reference);
            $refCheck->execute();
            $refCheck->store_result();

            if ($refCheck->num_rows === 0) {
                $refCheck->close();

                // Start transaction to ensure both updates happen together
                $con->begin_transaction();

                try {
                    // 2. Update Wallet Balance
                    $stmt = $con->prepare("UPDATE wallets SET balance = balance + ? WHERE student_id = ?");
                    $stmt->bind_param("di", $amount, $student_id);
                    $stmt->execute();

                    // 3. Log the transaction history
                    $log = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, reference, type) VALUES (?, ?, ?, 'deposit')");
                    $log->bind_param("ids", $student_id, $amount, $reference);
                    $log->execute();

                    $con->commit();
                    error_log("SUCCESS: Wallet funded and logged for Student ID: $student_id (Ref: $reference)");
                } catch (Exception $e) {
                    $con->rollback();
                    error_log("DB ERROR: Failed to fund wallet for Ref: $reference - " . $e->getMessage());
                }
            } else {
                $refCheck->close();
                error_log("SKIPPED: Reference $reference already processed.");
            }
        }

        // ==========================================================
        // CASE B: REGULAR FEE PAYMENT (Your Original Logic)
        // ==========================================================
    } else {
        $status = 'approved';
        $paymentMethod = 'Paystack';
        $customFields = $data['metadata']['custom_fields'] ?? [];

        function getCustomField($fields, $displayName, $default = '')
        {
            foreach ($fields as $field) {
                if (isset($field['display_name']) && $field['display_name'] === $displayName) {
                    return $field['value'] ?? $default;
                }
            }
            return $default;
        }

        $student_id = getCustomField($customFields, 'Student ID', 'unknown');
        $studentno = getCustomField($customFields, 'Student Number', 'N/A');
        $studentName = getCustomField($customFields, 'Student Name', 'Unnamed Student');
        $feeType = getCustomField($customFields, 'Fees Type', 'General Payment');
        $discountUsed = getCustomField($customFields, 'Used Discount', 'No');
        $discountAmount = floatval(getCustomField($customFields, 'Discount Amount', 0.00));
        $discountPercent = floatval(getCustomField($customFields, 'Discount Percent', 0.00));
        $term = getCustomField($customFields, 'Term ID', $currentTermName);
        $session = getCustomField($customFields, 'Session ID', $currentSessionName);

        if ($student_id !== 'unknown' && $reference && $amount > 0) {
            $refCheck = mysqli_prepare($con, "SELECT id FROM payments WHERE reference = ?");
            mysqli_stmt_bind_param($refCheck, "s", $reference);
            mysqli_stmt_execute($refCheck);
            mysqli_stmt_store_result($refCheck);

            if (mysqli_stmt_num_rows($refCheck) === 0) {
                $sql = "INSERT INTO payments (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, discount_used, discount_amount, discount_percent, payment_method, term_id, session_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?)";
                $stmt = mysqli_prepare($con, $sql);
                mysqli_stmt_bind_param($stmt, "sssssdsssddsss", $student_id, $studentno, $studentName, $email, $reference, $amount, $status, $feeType, $discountUsed, $discountAmount, $discountPercent, $paymentMethod, $term, $session);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
            mysqli_stmt_close($refCheck);
        }
    }
}

// === Final response to Paystack ===
header('Content-Type: application/json');
http_response_code(200);
echo json_encode(['status' => 'received']);
exit;