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

// === Helper Functions ===
/**
 * Extracts custom metadata from Paystack payload
 */
function getCustomField($fields, $displayName, $default = '') {
    if (!is_array($fields)) return $default;
    foreach ($fields as $field) {
        if (isset($field['display_name']) && $field['display_name'] === $displayName) {
            return $field['value'] ?? $default;
        }
    }
    return $default;
}

// === Initialize Context ===
$stResult = resolveCurrentSessionTerm($con);
$currentSessionName = $stResult['session_name'];
$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'];
    $channel = $data['channel'] ?? '';

    // ==========================================================
    // 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) {
            $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();
                $con->begin_transaction();
                try {
                    $stmt = $con->prepare("UPDATE wallets SET balance = balance + ? WHERE student_id = ?");
                    $stmt->bind_param("di", $amount, $student_id);
                    $stmt->execute();

                    $log = $con->prepare("INSERT INTO wallet_transactions (student_id, amount, reference, type) VALUES (?, ?, ?, 'Deposit')");
                    $log->bind_param("ids", $student_id, $amount, $reference);
                    $log->execute();

                    // Fetch student details for the payments record
                    $stuStmt = $con->prepare("SELECT studentno, studentName FROM students WHERE id = ?");
                    $stuStmt->bind_param("i", $student_id);
                    $stuStmt->execute();
                    $stuRow = $stuStmt->get_result()->fetch_assoc();
                    $stuStmt->close();

                    $studentno   = $stuRow['studentno']   ?? 'N/A';
                    $studentName = $stuRow['studentName'] ?? 'Unknown';

                    $payStmt = $con->prepare(
                        "INSERT INTO payments (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, payment_method, term_id, session_id)
                         VALUES (?, ?, ?, ?, ?, ?, 'approved', 'Wallet Deposit', NOW(), 'Paystack', ?, ?)"
                    );
                    $payStmt->bind_param(
                        "issssdss",
                        $student_id, $studentno, $studentName,
                        $email, $reference, $amount,
                        $currentTermName, $currentSessionName
                    );
                    $payStmt->execute();
                    $payStmt->close();

                    $con->commit();
                    error_log("SUCCESS: Wallet funded for Student ID: $student_id (Ref: $reference)");
                } catch (Exception $e) {
                    $con->rollback();
                    error_log("DB ERROR: Wallet fund failed - " . $e->getMessage());
                }
            } else {
                $refCheck->close();
            }
        }
    } 
    // ==========================================================
    // CASE B: DVA BANK TRANSFER (Dedicated Virtual Account)
    // ==========================================================
    elseif ($channel === 'dedicated_nuban') {
        $dupCheck = $con->prepare("SELECT id FROM payments WHERE reference = ?");
        $dupCheck->bind_param('s', $reference);
        $dupCheck->execute();
        $dupCheck->store_result();
        $alreadyDone = $dupCheck->num_rows > 0;
        $dupCheck->close();

        if (!$alreadyDone) {
            // Get the customer code from the webhook data to identify which account type received the transfer
            $webhookCustomerCode = $data['customer']['customer_code'] ?? '';

            // Find the payment_type for this customer code
            $typeStmt = $con->prepare(
                "SELECT payment_type FROM school_virtual_accounts WHERE paystack_customer_id = ? AND is_active = 1 LIMIT 1"
            );
            $typeStmt->bind_param('s', $webhookCustomerCode);
            $typeStmt->execute();
            $typeRow = $typeStmt->get_result()->fetch_assoc();
            $typeStmt->close();

            $paymentType = $typeRow['payment_type'] ?? null;

            if ($paymentType) {
                // Match pending payment by amount + payment_type + not expired + not processed
                $pendingStmt = $con->prepare(
                    "SELECT * FROM dva_pending_payments
                     WHERE amount = ? AND payment_type = ? AND expires_at >= NOW()
                     AND (processed = 0 OR processed IS NULL)
                     ORDER BY created_at ASC LIMIT 1"
                );
                $pendingStmt->bind_param('ds', $amount, $paymentType);
                $pendingStmt->execute();
                $pendingRow = $pendingStmt->get_result()->fetch_assoc();
                $pendingStmt->close();
            } else {
                // Fallback: match by amount only if customer code not found
                $pendingStmt = $con->prepare(
                    "SELECT * FROM dva_pending_payments
                     WHERE amount = ? AND expires_at >= NOW()
                     AND (processed = 0 OR processed IS NULL)
                     ORDER BY created_at ASC LIMIT 1"
                );
                $pendingStmt->bind_param('d', $amount);
                $pendingStmt->execute();
                $pendingRow = $pendingStmt->get_result()->fetch_assoc();
                $pendingStmt->close();
            }

            if ($pendingRow) {
                $insertStmt = $con->prepare(
                    "INSERT INTO payments (student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, payment_method, term_id, session_id)
                     VALUES (?, ?, ?, ?, ?, ?, 'approved', ?, NOW(), 'Bank Transfer', ?, ?)"
                );
                $insertStmt->bind_param(
                    'sssssdssss',
                    $pendingRow['student_id'], $pendingRow['studentno'], $pendingRow['studentName'],
                    $pendingRow['email'], $reference, $amount,
                    $pendingRow['fee_type'], $pendingRow['term_id'], $pendingRow['session_id']
                );

                if ($insertStmt->execute()) {
                    $markStmt = $con->prepare("UPDATE dva_pending_payments SET processed = 1, paystack_reference = ? WHERE id = ?");
                    $markStmt->bind_param('si', $reference, $pendingRow['id']);
                    $markStmt->execute();
                    $markStmt->close();
                    error_log("DVA Webhook: Payment recorded for ref {$reference}, type {$paymentType}, amount ₦{$amount}");
                }
                $insertStmt->close();
            } else {
                error_log("DVA Webhook: No matching pending payment for amount ₦{$amount}, type {$paymentType} (ref: {$reference})");
            }
        }
    }
    // ==========================================================
    // CASE C: REGULAR FEE PAYMENT (Standard Checkout)
    // ==========================================================
    else {
        $status = 'approved';
        $paymentMethod = 'Paystack';
        $customFields = $data['metadata']['custom_fields'] ?? [];

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