<?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) ?? [];
$enrollmentId = (int)($input['enrollment_id'] ?? 0);
$paymentId = trim($input['payment_id'] ?? '');
$amount = isset($input['amount']) ? (float)$input['amount'] : null;

if (!$enrollmentId) {
    echo json_encode(['success' => false, 'message' => 'enrollment_id is required']);
    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;
    }

    if ($amount !== null && abs($amount - $expectedAmount) > 0.01) {
        echo json_encode([
            'success' => false,
            'message' => 'Amount mismatch for enrollment',
            'expected' => $expectedAmount,
            'received' => $amount,
        ]);
        exit;
    }

    if ($paymentId === '') {
        $paymentId = 'squad-' . $enrollmentId . '-' . time();
    }

    $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', [
        'transaction_ref' => $paymentId,
        'amount' => $expectedAmount * 100,
    ]);

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