<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers/notification.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true) ?? [];
$reference = trim($input['reference'] ?? '');
$enrollmentId = (int)($input['enrollment_id'] ?? 0);

if ($reference === '' || !$enrollmentId) {
    echo json_encode(['success' => false, 'message' => 'reference and enrollment_id are required']);
    exit;
}

if (!defined('SQUAD_SECRET_KEY') || !SQUAD_SECRET_KEY || strpos(SQUAD_SECRET_KEY, 'your-squad') !== false) {
    echo json_encode(['success' => false, 'message' => 'Squad secret key is not configured']);
    exit;
}

try {
    $db = Database::getInstance();
    $enrollment = $db->get('SELECT * FROM course_enrollments WHERE id = ?', [$enrollmentId]);
    if (!$enrollment) {
        echo json_encode(['success' => false, 'message' => 'Enrollment not found']);
        exit;
    }

    if ($enrollment['payment_status'] !== 'pending') {
        echo json_encode(['success' => false, 'message' => 'Enrollment is not pending payment']);
        exit;
    }

    $expectedAmount = (float)($enrollment['payment_amount'] ?? 0.0);
    if ($expectedAmount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Enrollment has no payable amount']);
        exit;
    }

    $base = defined('SQUAD_API_BASE') ? SQUAD_API_BASE : 'https://sandbox-api.squadco.com';
    // NOTE: Check Squad docs for the exact verify endpoint path and payload.
    $verifyUrl = rtrim($base, '/') . '/transaction/verify';

    $payload = [
        'transaction_reference' => $reference,
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $verifyUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . SQUAD_SECRET_KEY,
        'Content-Type: application/json',
    ]);

    $response = curl_exec($ch);
    $errno = curl_errno($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($errno) {
        echo json_encode(['success' => false, 'message' => 'Squad verify failed: ' . $err]);
        exit;
    }

    $data = json_decode($response, true);
    if (!is_array($data) || empty($data['success']) || $data['success'] !== true) {
        echo json_encode([
            'success' => false,
            'message' => 'Squad returned error on verify',
            'response' => (APP_ENV === 'development') ? $data : null,
        ]);
        exit;
    }

    $refData = $data['data'] ?? null;
    if (!is_array($refData)) {
        echo json_encode(['success' => false, 'message' => 'Unexpected verify response structure from Squad']);
        exit;
    }

    // Squad responses in docs show `amount` in the smallest currency unit (e.g. kobo)
    $paidAmountBase = isset($refData['amount']) ? (float)$refData['amount'] : 0.0;
    $paidAmount = $paidAmountBase / 100.0;

    if ($paidAmount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid amount in Squad verify response']);
        exit;
    }

    $hasInstallments = $db->get('SELECT id FROM enrollment_installments WHERE enrollment_id = ? LIMIT 1', [$enrollmentId]);

    if ($hasInstallments) {
        $inst = $db->get('SELECT * FROM enrollment_installments WHERE enrollment_id = ? AND status = ? ORDER BY installment_no ASC LIMIT 1', [$enrollmentId, 'pending']);
        if (!$inst) {
            echo json_encode(['success' => false, 'message' => 'No pending installment found for this enrollment']);
            exit;
        }

        if (abs($paidAmount - (float)$inst['amount']) > 0.01) {
            echo json_encode([
                'success' => false,
                'message' => 'Amount mismatch between Squad and installment',
                'paid' => $paidAmount,
                'expected' => (float)$inst['amount'],
            ]);
            exit;
        }

        $paymentId = $refData['transaction_ref'] ?? $reference;

        // Mark installment as paid
        $db->update('enrollment_installments', [
            'status' => 'paid',
            'payment_id' => $paymentId,
            'gateway' => 'squad',
            'paid_at' => formatDate(),
        ], 'id = ?', [$inst['id']]);

        // Check for remaining installments
        $next = $db->get('SELECT * FROM enrollment_installments WHERE enrollment_id = ? AND status = ? ORDER BY installment_no ASC LIMIT 1', [$enrollmentId, 'pending']);

        if ($next) {
            $db->update('course_enrollments', [
                'payment_status' => 'pending',
                'payment_id' => $paymentId,
                'status' => 'active',
                'payment_amount' => (float)$next['amount'],
            ], 'id = ?', [$enrollmentId]);
        } else {
            $db->update('course_enrollments', [
                'payment_status' => 'paid',
                'payment_id' => $paymentId,
                'status' => 'active',
            ], 'id = ?', [$enrollmentId]);

            $db->query('UPDATE courses SET enrollment_count = enrollment_count + 1 WHERE id = ?', [$enrollment['course_id']]);
        }
    } else {
        if (abs($paidAmount - $expectedAmount) > 0.01) {
            echo json_encode([
                'success' => false,
                'message' => 'Amount mismatch between Squad and enrollment',
                'paid' => $paidAmount,
                'expected' => $expectedAmount,
            ]);
            exit;
        }

        $paymentId = $refData['transaction_ref'] ?? $reference;

        $db->update('course_enrollments', [
            'payment_status' => 'paid',
            'payment_id' => $paymentId,
            'status' => 'active',
        ], 'id = ?', [$enrollmentId]);

        $db->query('UPDATE courses SET enrollment_count = enrollment_count + 1 WHERE id = ?', [$enrollment['course_id']]);
    }

    // send invoice email
    sendEnrollmentInvoice($enrollmentId, 'squad', $refData);

    echo json_encode(['success' => true, 'data' => $refData]);
    exit;
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
