<?php
/**
 * RentRev AI - Application Bootstrap & Router
 */

session_start();

// Load configuration
$configFile = __DIR__ . '/../config/config.php';
if (!file_exists($configFile)) {
    header('Location: install.php');
    exit;
}
require_once $configFile;

// Set timezone
date_default_timezone_set(APP_TIMEZONE);

// Error reporting
if (APP_DEBUG) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
}

// Autoload helpers
require_once APP_PATH . '/models/Database.php';
require_once APP_PATH . '/helpers/functions.php';
require_once APP_PATH . '/helpers/Auth.php';
require_once APP_PATH . '/helpers/CSRF.php';
require_once APP_PATH . '/helpers/Validator.php';

// Initialize database
$db = Database::getInstance();

// CSRF Protection
CSRF::init();

// Router
$page = $_GET['page'] ?? 'dashboard';
$action = $_GET['action'] ?? 'index';
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;

// Auth check
$publicPages = ['login', 'forgot-password', 'reset-password'];
if (!in_array($page, $publicPages) && !Auth::check()) {
    redirect('?page=login');
}

// Load current user
$currentUser = Auth::check() ? Auth::user() : null;

// Route to controller
$controllerMap = [
    'login' => 'AuthController',
    'forgot-password' => 'AuthController',
    'reset-password' => 'AuthController',
    'logout' => 'AuthController',
    'dashboard' => 'DashboardController',
    'properties' => 'PropertyController',
    'units' => 'UnitController',
    'tenants' => 'TenantController',
    'owners' => 'OwnerController',
    'leases' => 'LeaseController',
    'payments' => 'PaymentController',
    'rent-collection' => 'PaymentController',
    'maintenance' => 'MaintenanceController',
    'work-orders' => 'WorkOrderController',
    'vendors' => 'VendorController',
    'documents' => 'DocumentController',
    'communications' => 'CommunicationController',
    'leads' => 'LeadController',
    'reports' => 'ReportController',
    'ai-center' => 'AIController',
    'integrations' => 'IntegrationController',
    'api-center' => 'APIController',
    'users' => 'UserController',
    'roles' => 'RoleController',
    'billing' => 'BillingController',
    'settings' => 'SettingController',
    'profile' => 'ProfileController',
    'notifications' => 'NotificationController',
    'expenses' => 'ExpenseController',
];

$controllerName = $controllerMap[$page] ?? null;

if ($controllerName) {
    $controllerFile = APP_PATH . "/controllers/{$controllerName}.php";
    if (file_exists($controllerFile)) {
        require_once $controllerFile;
        $controller = new $controllerName();
        
        // Map actions
        $method = match($action) {
            'index' => 'index',
            'create' => 'create',
            'store' => 'store',
            'show', 'view' => 'show',
            'edit' => 'edit',
            'update' => 'update',
            'delete' => 'delete',
            'export' => 'export',
            default => $action
        };
        
        if (method_exists($controller, $method)) {
            $controller->$method($id);
        } else {
            $controller->index();
        }
    } else {
        http_response_code(404);
        include APP_PATH . '/views/errors/404.php';
    }
} else {
    http_response_code(404);
    include APP_PATH . '/views/errors/404.php';
}
