<?php
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/database.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    exit;
}

// Read and decode JSON input
$input = json_decode(file_get_contents('php://input'), true);

// CSRF (token arrives via X-CSRF-Token header from register.php)
require_csrf(true, is_array($input) ? $input : null);

$eventId = $input['eventId'] ?? '';
$fullName = $input['fullName'] ?? '';
$email = $input['email'] ?? '';
$mobileNumber = $input['mobileNumber'] ?? '';
$city = $input['city'] ?? '';
$college = $input['college'] ?? '';

if (!$eventId || !$fullName || !$email || !$mobileNumber || !$city || !$college) {
    http_response_code(400);
    echo json_encode(['error' => 'All fields are required.']);
    exit;
}

if (!preg_match('/^[0-9]{10}$/', $mobileNumber)) {
    http_response_code(400);
    echo json_encode(['error' => 'Mobile number must be exactly 10 digits and contain only numbers.']);
    exit;
}

if (!preg_match('/^[a-zA-Z\s\.]+$/', $fullName)) {
    http_response_code(400);
    echo json_encode(['error' => 'Full name must contain only alphabets, spaces, or periods.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid email format. Only alphabets, numbers, and symbols like @, ., _, -, + are allowed.']);
    exit;
}

if (!preg_match('/^[a-zA-Z\s]+$/', $city)) {
    http_response_code(400);
    echo json_encode(['error' => 'City must contain only alphabets and spaces.']);
    exit;
}

if (!preg_match('/^[a-zA-Z\s\.\,\-\/\&\(\)]+$/', $college)) {
    http_response_code(400);
    echo json_encode(['error' => 'College / Organization must contain only alphabets, spaces, and standard punctuation (no numbers).']);
    exit;
}

$pdo = getDatabaseConnection();

// Check if already registered (with successful payment or registration)
try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE email = ? AND eventId = ?");
    $stmt->execute([$email, $eventId]);
    $count = $stmt->fetchColumn();

    if ($count > 0) {
        http_response_code(400);
        echo json_encode(['error' => 'You have already registered for this event with this email address.']);
        exit;
    }

    // Fetch Event details
    $evtStmt = $pdo->prepare("SELECT * FROM events WHERE id = ? AND status = 'PUBLISHED'");
    $evtStmt->execute([$eventId]);
    $event = $evtStmt->fetch(PDO::FETCH_ASSOC);

    if (!$event) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid or unpublished event selected.']);
        exit;
    }

    $fee = floatval($event['registrationFee']);

    // Case 1: Free Event (Fee = 0)
    if ($fee <= 0) {
        // Generate unique Registration ID
        do {
            $regIdCode = strtoupper(substr($event['slug'], 0, 3)) . rand(10000, 99999);
            $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM registrations WHERE registrationId = ?");
            $checkStmt->execute([$regIdCode]);
            $exists = $checkStmt->fetchColumn();
        } while ($exists > 0);

        // Insert Registration
        $insertReg = $pdo->prepare("INSERT INTO registrations (id, registrationId, eventId, fullName, email, mobileNumber, college, city) VALUES (UUID(), ?, ?, ?, ?, ?, ?, ?)");
        $insertReg->execute([$regIdCode, $eventId, $fullName, $email, $mobileNumber, $college, $city]);

        // Fetch inserted registration UUID
        $regStmt = $pdo->prepare("SELECT id FROM registrations WHERE registrationId = ?");
        $regStmt->execute([$regIdCode]);
        $regRecord = $regStmt->fetch(PDO::FETCH_ASSOC);

        // Insert Payment record
        $orderId = "free_" . $regIdCode . "_" . time();
        $insertPay = $pdo->prepare("INSERT INTO payments (id, registrationId, amount, currency, razorpayOrderId, status) VALUES (UUID(), ?, 0.00, 'INR', ?, 'SUCCESSFUL')");
        $insertPay->execute([$regRecord['id'], $orderId]);

        echo json_encode([
            'status' => 'success',
            'isFree' => true,
            'registrationId' => $regIdCode
        ]);
        exit;
    }

    // Case 2: Paid Event (Fee > 0) -> Call Razorpay Orders API
    $amountInPaise = (int)($fee * 100);
    $receipt = 'rcpt_' . bin2hex(random_bytes(4)) . '_' . time();

    $payload = [
        'amount' => $amountInPaise,
        'currency' => 'INR',
        'receipt' => $receipt,
        'notes' => [
            'fullName' => $fullName,
            'email' => $email,
            'mobileNumber' => $mobileNumber,
            'city' => $city,
            'college' => $college,
            'eventId' => $eventId
        ]
    ];

    $ch = curl_init('https://api.razorpay.com/v1/orders');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    
    $response = curl_exec($ch);
    $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpStatusCode !== 200) {
        error_log("Razorpay Order API Failed: " . $response);
        http_response_code(500);
        echo json_encode(['error' => 'Failed to initialize payment gateway order. Please try again.']);
        exit;
    }

    $razorpayOrder = json_decode($response, true);

    echo json_encode([
        'status' => 'success',
        'isFree' => false,
        'razorpayOrderId' => $razorpayOrder['id'],
        'amount' => $amountInPaise,
        'keyId' => RAZORPAY_KEY_ID,
        'registrationDetails' => $payload['notes']
    ]);
    exit;

} catch (Exception $e) {
    error_log("Order Initialization Exception: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'An internal server error occurred. Please try again later.']);
    exit;
}
