<?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' => true,
    'error' => '',
    'registration_mode' => 'invite_only',
    'site_name' => 'EventPortal',
    'logo_url' => '',
    'default_emp_code' => '',
    'invitation' => null,
    'ref' => ''
];

try {
    $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['registration_mode'] = $configs['registration_mode'] ?? 'invite_only';
    
    $token = isset($_GET['token']) ? trim($_GET['token']) : '';
    $ref = isset($_GET['ref']) ? trim($_GET['ref']) : '';
    $response['ref'] = $ref;
    
    // Generate default employee code
    $prefix = $configs['emp_code_prefix'] ?? 'REPL';
    $length = (int)($configs['emp_code_length'] ?? 15);
    $default_type = $configs['emp_code_default_type'] ?? 'generated';
    $custom_val = $configs['emp_code_custom_value'] ?? 'EMP-DEFAULT';

    if ($default_type === 'generated') {
        $unique = false;
        $attempts = 0;
        while (!$unique && $attempts < 15) {
            $temp_code = generateEmployeeCode($prefix, $length);
            $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
            $check_code->execute([$temp_code]);
            if ($check_code->fetchColumn() == 0) {
                $response['default_emp_code'] = $temp_code;
                $unique = true;
            }
            $attempts++;
        }
    } else {
        $temp_code = $custom_val;
        $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
        $check_code->execute([$temp_code]);
        if ($check_code->fetchColumn() == 0) {
            $response['default_emp_code'] = $temp_code;
        } else {
            $unique = false;
            $suffix = 1;
            while (!$unique && $suffix < 100) {
                $s_code = $temp_code . '-' . $suffix;
                $check_code = $pdo->prepare("SELECT COUNT(*) FROM users WHERE employee_code = ?");
                $check_code->execute([$s_code]);
                if ($check_code->fetchColumn() == 0) {
                    $response['default_emp_code'] = $s_code;
                    $unique = true;
                }
                $suffix++;
            }
        }
    }
    
    if (!empty($token)) {
        $stmt = $pdo->prepare("SELECT * FROM user_invitations WHERE token = ? AND status = 'pending'");
        $stmt->execute([$token]);
        $invitation = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($invitation) {
            $response['invitation'] = $invitation;
        } elseif ($response['registration_mode'] !== 'open') {
            $response['success'] = false;
            $response['error'] = "This user registration invitation link is invalid or has already been used.";
        }
    } elseif ($response['registration_mode'] !== 'open') {
        $response['success'] = false;
        $response['error'] = "Direct registrations are disabled. You must have a valid registration invitation link to onboard.";
    }
} catch (PDOException $e) {
    $response['success'] = false;
    $response['error'] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
