<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'registration' => null,
    'kyc' => null,
    'site_name' => 'EventPortal',
    'logo_url' => '',
    'user' => null
];

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$currentUser = getCurrentUser();
$response['user'] = [
    'username' => $currentUser['username'],
    'email' => $currentUser['email']
];

$eventId = isset($_GET['event_id']) ? (int)$_GET['event_id'] : 0;

if ($eventId <= 0) {
    $response['message'] = "Invalid Event ID.";
    echo json_encode($response);
    exit();
}

try {
    $stmt = $pdo->prepare("
        SELECT e.*, r.registered_at, r.base_price, r.gst_rate as reg_gst_rate, r.gst_amount, r.total_payable, u.username as organizer_name, r.id as reg_id, e.price
        FROM events e
        JOIN registrations r ON e.id = r.event_id
        LEFT JOIN users u ON e.created_by = u.id
        WHERE e.id = ? AND r.user_id = ?
    ");
    $stmt->execute([$eventId, $currentUser['id']]);
    $registration = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$registration) {
        $response['message'] = "No registration record found for this event.";
        echo json_encode($response);
        exit();
    }

    $response['registration'] = $registration;

    // Fetch KYC
    $stmt_kyc = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt_kyc->execute([$currentUser['id']]);
    $response['kyc'] = $stmt_kyc->fetch(PDO::FETCH_ASSOC) ?: null;

    // Fetch configs
    $stmt_c = $pdo->query("SELECT key, value FROM system_settings");
    $configs = $stmt_c->fetchAll(PDO::FETCH_KEY_PAIR) ?: [];
    $response['site_name'] = $configs['site_name'] ?? 'EventPortal';
    $response['logo_url'] = $configs['site_logo'] ?? '';
    $response['company_address'] = $configs['company_address'] ?? 'Bandra Kurla Complex, Mumbai, Maharashtra - 400051';
    $response['company_gstin'] = $configs['company_gstin'] ?? '27AAACE1234F1Z0';
    
    $response['success'] = true;
} catch (PDOException $e) {
    $response['message'] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
