<?php
session_start();

// Simple configuration - MUST BE AT THE TOP
define('APP_ROOT', dirname(__DIR__));
define('STORAGE_PATH', APP_ROOT . '/storage');
define('UPLOAD_PATH', STORAGE_PATH . '/uploads');
define('VIEWS_PATH', APP_ROOT . '/Resources/views');

// Load environment variables FIRST
if (file_exists(APP_ROOT . '/.env')) {
    $env = parse_ini_file(APP_ROOT . '/.env');
    foreach ($env as $key => $value) {
        $_ENV[$key] = $value;
        putenv("$key=$value");
    }
}

// ==================== SIMPLE AUTH SHIM ====================
// Provides Auth::check(), Auth::id(), Auth::tenantId(), Auth::user(), Auth::logout()
// so legacy controllers using Auth::... don't crash.
if (!class_exists('Auth')) {
    class Auth
    {
        public static function check(): bool
        {
            return !empty($_SESSION['user_id']);
        }

        public static function id()
        {
            return $_SESSION['user_id'] ?? null;
        }

        public static function tenantId()
        {
            return $_SESSION['tenant_id'] ?? null;
        }

        public static function user()
        {
            // If you store the whole user record in session, return it.
            // Otherwise, you can fetch from DB here if needed.
            return $_SESSION['user'] ?? null;
        }

        public static function logout(): void
        {
            session_destroy();
        }
    }
}

// ==================== DATABASE ====================
class Database
{
    private static $connection = null;

    public static function getConnection()
    {
        if (self::$connection === null) {
            try {
                self::$connection = new PDO(
                    'mysql:host=localhost;dbname=ai_run;charset=utf8mb4',
                    'root',
                    '',
                    [
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                        PDO::ATTR_EMULATE_PREPARES   => false
                    ]
                );
            } catch (PDOException $e) {
                error_log("Database connection failed: " . $e->getMessage());
                throw new Exception("Database connection failed");
            }
        }
        return self::$connection;
    }
}

// Get database connection
try {
    $pdo = Database::getConnection();
} catch (Exception $e) {
    die("Database connection failed: " . $e->getMessage());
}

// ==================== MANUAL CLASS LOADING ====================
$requiredClasses = [
    'BaseController'            => '/app/Controllers/BaseController.php',
    'AuthController'            => '/app/Controllers/AuthController.php',
    'DashboardController'       => '/app/Controllers/DashboardController.php',
    'FormsController'           => '/app/Controllers/FormsController.php',
    'LeadsController'           => '/app/Controllers/LeadsController.php',
    'AnalyticsController'       => '/app/Controllers/AnalyticsController.php',
    'TasksController'           => '/app/Controllers/TasksController.php',
    'TaskAssignmentsController' => '/app/Controllers/TaskAssignmentsController.php',
    'WeeklyReportsController'   => '/app/Controllers/WeeklyReportsController.php',
    'AIService'                 => '/app/Services/AIService.php',
    'FormBuilderService'        => '/app/Services/FormBuilderService.php',
];

foreach ($requiredClasses as $class => $path) {
    $file = APP_ROOT . $path;
    if (file_exists($file)) {
        require_once $file;
        error_log("Loaded: " . $class);
    } else {
        error_log("Class file not found: " . $file);
    }
}

// ==================== VIEW CLASS ====================
class View
{
    private $basePath;

    public function __construct($basePath = null)
    {
        $this->basePath = $basePath ?: VIEWS_PATH . '/';
    }

    public function render($view, $data = [])
    {
        $viewFile = $this->basePath . $view . '.php';

        if (!file_exists($viewFile)) {
            throw new Exception("View file not found: " . $viewFile);
        }

        extract($data);
        ob_start();
        include $viewFile;
        $content = ob_get_clean();

        // Determine which layout to use
        $layout = 'layouts/main.php'; // Default layout with sidebar

        // Landing page uses auth layout (no sidebar)
        if ($view === 'pages/landing') {
            $layout = 'layouts/auth.php';
        }
        // Dashboard/pages use main layout (with sidebar)
        else if (strpos($view, 'pages/') === 0) {
            $layout = 'layouts/main.php';
        }
        // Auth pages use auth layout (no sidebar)
        else if (strpos($view, 'auth/') === 0) {
            $layout = 'layouts/auth.php';
        }

        $layoutFile = $this->basePath . $layout;
        if (file_exists($layoutFile)) {
            $pageTitle = $data['pageTitle'] ?? ($data['title'] ?? 'LeadIntelligence AI');
            ob_start();
            include $layoutFile;
            return ob_get_clean();
        }

        return $content;
    }
}

// ==================== SESSION CLASS ====================
class Session
{
    public function __construct()
    {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public function set($key, $value)
    {
        $_SESSION[$key] = $value;
    }

    public function get($key, $default = null)
    {
        return $_SESSION[$key] ?? $default;
    }

    public function has($key)
    {
        return isset($_SESSION[$key]);
    }

    public function remove($key)
    {
        unset($_SESSION[$key]);
    }

    public function destroy()
    {
        session_destroy();
    }

    public function getFlash($key)
    {
        $value = $this->get($key);
        $this->remove($key);
        return $value;
    }

    public function setFlash($key, $value)
    {
        $this->set($key, $value);
    }
}

// ==================== REQUEST CLASS ====================
class Request
{
    public function get($key, $default = null)
    {
        return $_GET[$key] ?? $default;
    }

    public function post($key, $default = null)
    {
        return $_POST[$key] ?? $default;
    }

    public function input($key, $default = null)
    {
        return $this->post($key, $this->get($key, $default));
    }

    public function all()
    {
        return array_merge($_GET, $_POST);
    }

    public function isPost()
    {
        return $_SERVER['REQUEST_METHOD'] === 'POST';
    }

    public function isGet()
    {
        return $_SERVER['REQUEST_METHOD'] === 'GET';
    }

    public function isAjax()
    {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
            strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }

    public function getMethod()
    {
        return $_SERVER['REQUEST_METHOD'];
    }

    public function getUri()
    {
        return $_SERVER['REQUEST_URI'] ?? '/';
    }

    public function getPath()
    {
        $uri = $this->getUri();
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }
        return $uri;
    }
}

// ==================== ROUTER CLASS ====================
class Router
{
    private $routes = [];
    private $basePath = '';

    public function setBasePath($basePath)
    {
        $this->basePath = $basePath;
    }

    public function addRoute($method, $path, $handler)
    {
        $this->routes[] = [
            'method'  => strtoupper($method),
            'path'    => $this->basePath . $path,
            'pattern' => $this->convertToRegex($this->basePath . $path),
            'handler' => $handler
        ];
    }

    private function convertToRegex($path)
    {
        $pattern = preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $path);
        return '#^' . $pattern . '$#';
    }

    public function route($request)
    {
        $method = $request->getMethod();
        $path   = $request->getPath();

        foreach ($this->routes as $route) {
            if ($route['method'] === $method && preg_match($route['pattern'], $path, $matches)) {
                $params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);

                if (is_callable($route['handler'])) {
                    return call_user_func($route['handler'], $request, ...array_values($params));
                } elseif (is_string($route['handler'])) {
                    return $this->callControllerMethod($route['handler'], $request, $params);
                }
            }
        }

        http_response_code(404);
        if ($request->isAjax()) {
            header('Content-Type: application/json');
            return json_encode(['error' => 'Page not found']);
        }
        return "Page not found";
    }

    private function callControllerMethod($handler, $request, $params)
    {
        list($controller, $method) = explode('@', $handler);

        if (!class_exists($controller)) {
            throw new Exception("Controller not found: {$controller}");
        }

        $controllerInstance = new $controller();

        if (!method_exists($controllerInstance, $method)) {
            throw new Exception("Method not found: {$controller}@{$method}");
        }

        return call_user_func_array([$controllerInstance, $method], array_merge([$request], array_values($params)));
    }
}

// ==================== INITIALIZE CORE COMPONENTS ====================
$view    = new View();
$session = new Session();
$request = new Request();
$router  = new Router();

// Base path for routing (matches your public folder URL)
$router->setBasePath('/lead-management/public');

// ==================== AUTH ROUTES ====================
$router->addRoute('GET', '/login', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->showLogin();
});

$router->addRoute('POST', '/login', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->login($request);
});

$router->addRoute('GET', '/logout', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->logout();
});

$router->addRoute('GET', '/register', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->showRegister();
});

$router->addRoute('POST', '/register', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->register($request);
});

$router->addRoute('GET', '/forgot-password', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->showForgotPassword();
});

$router->addRoute('POST', '/forgot-password', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->forgotPassword($request);
});

// Email verification routes
$router->addRoute('GET', '/verify-email', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->verifyEmail($request);
});

$router->addRoute('GET', '/resend-verification', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->resendVerification();
});

// Password reset routes
$router->addRoute('GET', '/reset-password', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->showResetPassword();
});

$router->addRoute('POST', '/reset-password', function ($request) use ($pdo) {
    $controller = new AuthController($pdo);
    return $controller->resetPassword($request);
});

// ==================== PUBLIC ROUTES ====================
$router->addRoute('GET', '/', function ($request) use ($view) {
    return $view->render('pages/landing', ['title' => 'Lead Management System']);
});

// Public form embed + submit
$router->addRoute('GET', '/forms/{id}/embed', function ($request, $id) use ($pdo) {
    $controller = new FormsController($pdo);
    return $controller->embed($id);
});

$router->addRoute('POST', '/forms/{id}/submit', function ($request, $id) use ($pdo) {
    $controller = new FormsController($pdo);
    return $controller->submit($id);
});

// ==================== PROTECTED ROUTES: DASHBOARD ====================
$router->addRoute('GET', '/app', function ($request) use ($view, $pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }

    $tenantId = $_SESSION['tenant_id'];

    try {
        $stats = [];

        // Total leads
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM leads WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $stats['total_leads'] = (int)$stmt->fetchColumn();

        // Total forms
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM forms WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $stats['total_forms'] = (int)$stmt->fetchColumn();

        // Leads today
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM leads WHERE tenant_id = ? AND DATE(created_at) = CURDATE()");
        $stmt->execute([$tenantId]);
        $stats['leads_today'] = (int)$stmt->fetchColumn();

        // High score leads (score >= 80)
        $stmt = $pdo->prepare("SELECT COUNT(*) as total FROM leads WHERE tenant_id = ? AND ai_score >= 80");
        $stmt->execute([$tenantId]);
        $stats['high_score_leads'] = (int)$stmt->fetchColumn();

        // Recent leads
        $stmt = $pdo->prepare("
            SELECT 
                l., 
                CONCAT(l.first_name, ' ', l.last_name) AS full_name,
                l.ai_score AS score
            FROM leads l 
            WHERE l.tenant_id = ? 
            ORDER BY l.created_at DESC 
            LIMIT 5
        ");
        $stmt->execute([$tenantId]);
        $leads = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        error_log("Dashboard data error: " . $e->getMessage());
        $stats = [
            'total_leads'      => 0,
            'total_forms'      => 0,
            'leads_today'      => 0,
            'high_score_leads' => 0
        ];
        $leads = [];
    }

    return $view->render('pages/dashboard', [
        'title'       => 'Dashboard - LeadIntelligence AI',
        'pageTitle'   => 'Dashboard',
        'stats'       => $stats,
        'leads'       => $leads,
        'currentPage' => 'dashboard',
    ]);
});

$router->addRoute('GET', '/app/dashboard', function ($request) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    header('Location: /lead-management/public/app');
    exit;
});

// ==================== LEADS MANAGEMENT ROUTES ====================
$router->addRoute('GET', '/app/leads', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->index();
});

// Lead detail (SkyBlue lead show page with behavior timeline & AI panel)
$router->addRoute('GET', '/app/leads/{id}', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->show($id);
});

$router->addRoute('GET', '/app/leads/create', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->create();
});

$router->addRoute('POST', '/app/leads/store', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->store();
});

$router->addRoute('GET', '/app/leads/{id}/edit', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->edit($id);
});

$router->addRoute('POST', '/app/leads/{id}/update', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->update($id);
});

$router->addRoute('GET', '/app/leads/{id}/delete', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->delete($id);
});

// Leads stats API (for dashboard widgets / charts)
$router->addRoute('GET', '/app/leads/stats', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'error' => 'Unauthorized']);
    }
    $controller = new LeadsController($pdo);
    return $controller->getStats();
});

// AI Lead routes (Score, Generate Email, Behavior Analysis)
$router->addRoute('POST', '/app/leads/{id}/score', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->scoreLead($id);
});

$router->addRoute('POST', '/app/leads/{id}/generate-email', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->generateEmail($id);
});

$router->addRoute('GET', '/app/leads/{id}/analyze-behavior', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new LeadsController($pdo);
    return $controller->analyzeBehavior($id);
});

// ==================== TASKS MANAGEMENT ROUTES ====================

$router->addRoute('GET', '/app/tasks', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->index();
});

$router->addRoute('GET', '/app/tasks/create', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->create();
});

$router->addRoute('POST', '/app/tasks/store', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->store();
});

$router->addRoute('GET', '/app/tasks/{id}', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->show($id);
});

$router->addRoute('GET', '/app/tasks/{id}/edit', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->edit($id);
});

$router->addRoute('POST', '/app/tasks/{id}/update', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->update($id);
});

$router->addRoute('GET', '/app/tasks/{id}/delete', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TasksController($pdo);
    return $controller->delete($id);
});

// ==================== TASK ASSIGNMENTS ROUTES ====================

$router->addRoute('POST', '/app/tasks/{id}/assign', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TaskAssignmentsController($pdo);
    return $controller->assign($id);
});

$router->addRoute('GET', '/app/my-assignments', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TaskAssignmentsController($pdo);
    return $controller->myAssignments();
});

$router->addRoute('GET', '/app/assignments/{id}', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new TaskAssignmentsController($pdo);
    return $controller->showAssignment($id);
});

// ==================== WEEKLY REPORTS ROUTES ====================

$router->addRoute('GET', '/app/weekly-reports', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new WeeklyReportsController($pdo);
    return $controller->index();
});

// AJAX: tasks for the given week (?week=YYYY-WW) or all if no param
$router->addRoute('GET', '/app/weekly-reports/tasks', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'Unauthorized']);
    }

    $week = $_GET['week'] ?? null;
    $controller = new WeeklyReportsController($pdo);
    return $controller->getUserTasks($week);
});

// AJAX: submit weekly report (create or update)
$router->addRoute('POST', '/app/weekly-reports/submit', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'Unauthorized']);
    }

    $controller = new WeeklyReportsController($pdo);
    return $controller->submit();
});

// AJAX: get weekly report for a specific week (?week=YYYY-WW)
$router->addRoute('GET', '/app/weekly-reports/report', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'Unauthorized']);
    }

    $week = $_GET['week'] ?? '';
    $controller = new WeeklyReportsController($pdo);
    return $controller->getWeeklyReport($week);
});

// AJAX: history (optional ?limit=10)
$router->addRoute('GET', '/app/weekly-reports/history', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'Unauthorized']);
    }

    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $controller = new WeeklyReportsController($pdo);
    return $controller->getReportHistory($limit);
});

// AJAX: user stats widget
$router->addRoute('GET', '/app/weekly-reports/stats', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'message' => 'Unauthorized']);
    }

    $controller = new WeeklyReportsController($pdo);
    return $controller->getUserStats();
});

// ==================== FORMS MANAGEMENT ROUTES ====================
$router->addRoute('GET', '/app/forms', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->index();
});

// SkyBlue form builder (create)
$router->addRoute('GET', '/app/forms/create', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->create();
});

// Builder save (new form) – matches JS fetch in formBuilder()
$router->addRoute('POST', '/app/forms/create', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->create(); // handles POST internally as before
});

// Builder edit (load existing)
$router->addRoute('GET', '/app/forms/{id}/edit', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->edit($id);
});

// Builder save (update existing) – matches JS fetch in formBuilder()
$router->addRoute('POST', '/app/forms/{id}/edit', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->edit($id);
});

// Form submissions list (SkyBlue-style page)
$router->addRoute('GET', '/app/forms/{id}/submissions', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->submissions($id);
});

// Form analytics (SkyBlue analytics page per form)
$router->addRoute('GET', '/app/forms/{id}/analytics', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->analytics($id);
});

$router->addRoute('POST', '/app/forms/{id}/update-status', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->updateStatus($id);
});

$router->addRoute('GET', '/app/forms/{id}/delete', function ($request, $id) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new FormsController($pdo);
    return $controller->delete($id);
});

// ==================== ANALYTICS / AI TOOLS ROUTES ====================

// Global analytics dashboard (SkyBlue analytics page)
$router->addRoute('GET', '/app/analytics', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new AnalyticsController($pdo);
    return $controller->index();
});

// (Optional) AI tools home page if you created AnalyticsController::aiTools()
$router->addRoute('GET', '/app/ai-tools', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        header('Location: /lead-management/public/login');
        exit;
    }
    $controller = new AnalyticsController($pdo);
    if (method_exists($controller, 'aiTools')) {
        return $controller->aiTools();
    }
    // Fallback: redirect to analytics if aiTools() not implemented
    header('Location: /lead-management/public/app/analytics');
    exit;
});

// ==================== API ROUTES ====================
$router->addRoute('POST', '/api/config/ai', function ($request) use ($pdo) {
    if (empty($_SESSION['user_id'])) {
        http_response_code(401);
        return json_encode(['success' => false, 'error' => 'Unauthorized']);
    }

    $data   = json_decode(file_get_contents('php://input'), true);
    $userId = $_SESSION['user_id'];

    try {
        $stmt = $pdo->prepare("
            INSERT INTO user_settings (user_id, ai_provider, api_key, updated_at) 
            VALUES (?, ?, ?, NOW()) 
            ON DUPLICATE KEY UPDATE 
                ai_provider = VALUES(ai_provider), 
                api_key     = VALUES(api_key), 
                updated_at  = VALUES(updated_at)
        ");

        $stmt->execute([
            $userId,
            $data['ai_provider'] ?? 'openai',
            $data['api_key'] ?? ''
        ]);

        $_SESSION['api_key'] = $data['api_key'] ?? '';

        return json_encode(['success' => true]);
    } catch (Exception $e) {
        error_log("API config error: " . $e->getMessage());
        return json_encode(['success' => false, 'error' => 'Failed to save configuration']);
    }
});

// ==================== HANDLE THE REQUEST ====================
try {
    $response = $router->route($request);

    if (is_string($response)) {
        echo $response;
    } elseif (is_array($response)) {
        header('Content-Type: application/json');
        echo json_encode($response);
    }
} catch (Exception $e) {
    http_response_code(500);
    error_log("Application error: " . $e->getMessage());

    if ($request->isAjax()) {
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Internal server error']);
    } else {
        echo "<h1>Application Error</h1>";
        echo "<p>Something went wrong. Please try again later.</p>";
        if (isset($_ENV['APP_DEBUG']) && $_ENV['APP_DEBUG'] === 'true') {
            echo "<pre>Error: " . htmlspecialchars($e->getMessage()) . "</pre>";
        }
    }
}
