<?php
/**
 * Simple Core Framework - One file to rule them all
 * Modular but not over-engineered
 */

// ==================== CONFIGURATION ====================
class Config {
    private static $loaded = false;
    private static $config = [];
    
    public static function load($path = null) {
        if (self::$loaded) return;
        
        $path = $path ?: dirname(__DIR__) . '/.env';
        if (file_exists($path)) {
            self::$config = parse_ini_file($path);
        }
        
        // Set defaults
        self::$config = array_merge([
            'DB_HOST' => 'localhost',
            'DB_NAME' => 'ai_run', 
            'DB_USER' => 'root',
            'DB_PASSWORD' => '',
            'APP_DEBUG' => false
        ], self::$config);
        
        self::$loaded = true;
    }
    
    public static function get($key, $default = null) {
        return self::$config[$key] ?? $default;
    }
}

// ==================== DATABASE ====================
class DB {
    private static $instance = null;
    
    public static function get() {
        if (self::$instance === null) {
            Config::load();
            
            $dsn = "mysql:host=" . Config::get('DB_HOST') . 
                   ";dbname=" . Config::get('DB_NAME') . 
                   ";charset=utf8mb4";
                   
            self::$instance = new PDO($dsn, 
                Config::get('DB_USER'), 
                Config::get('DB_PASSWORD'),
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false
                ]
            );
        }
        return self::$instance;
    }
}

// ==================== ROUTER ====================
class Router {
    private $routes = [];
    private $basePath = '';
    
    public function setBasePath($path) {
        $this->basePath = rtrim($path, '/');
    }
    
    public function add($method, $path, $handler) {
        $this->routes[] = [
            'method' => strtoupper($method),
            'path' => $this->basePath . $path,
            'pattern' => $this->pathToRegex($this->basePath . $path),
            'handler' => $handler
        ];
    }
    
    public function dispatch() {
        $method = $_SERVER['REQUEST_METHOD'];
        $path = $this->getCurrentPath();
        
        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);
                return $this->callHandler($route['handler'], $params);
            }
        }
        
        return $this->notFound();
    }
    
    private function pathToRegex($path) {
        $pattern = preg_replace('/\{(\w+)\}/', '(?P<$1>[^/]+)', $path);
        return '#^' . $pattern . '$#';
    }
    
    private function getCurrentPath() {
        $path = $_SERVER['REQUEST_URI'] ?? '/';
        if (($pos = strpos($path, '?')) !== false) {
            $path = substr($path, 0, $pos);
        }
        return $path;
    }
    
    private function callHandler($handler, $params) {
        if (is_callable($handler)) {
            return call_user_func_array($handler, array_values($params));
        }
        
        if (is_string($handler) && strpos($handler, '@') !== false) {
            list($controller, $method) = explode('@', $handler);
            if (class_exists($controller) && method_exists($controller, $method)) {
                $instance = new $controller();
                return call_user_func_array([$instance, $method], array_values($params));
            }
        }
        
        throw new Exception("Invalid route handler: " . print_r($handler, true));
    }
    
    private function notFound() {
        http_response_code(404);
        if ($this->isAjax()) {
            header('Content-Type: application/json');
            return json_encode(['error' => 'Not found']);
        }
        return "Page not found";
    }
    
    private function isAjax() {
        return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
               strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
    }
}

// ==================== VIEW RENDERER ====================
class View {
    private $basePath;
    
    public function __construct($basePath = null) {
        $this->basePath = $basePath ?: dirname(__DIR__) . '/Resources/views/';
    }
    
    public function render($view, $data = []) {
        $viewFile = $this->basePath . $view . '.php';
        
        if (!file_exists($viewFile)) {
            throw new Exception("View not found: " . $viewFile);
        }
        
        extract($data);
        ob_start();
        include $viewFile;
        $content = ob_get_clean();
        
        // Use layout
        $layout = $this->getLayout($view);
        $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;
    }
    
    private function getLayout($view) {
        if ($view === 'pages/landing') return 'layouts/auth.php';
        if (strpos($view, 'pages/') === 0) return 'layouts/main.php';
        if (strpos($view, 'auth/') === 0) return 'layouts/auth.php';
        return 'layouts/main.php';
    }
}

// ==================== HELPER FUNCTIONS ====================
function url($path = '') {
    $base = '/lead-management/public';
    $path = ltrim($path, '/');
    return $base . ($path ? '/' . $path : '');
}

function asset($path = '') {
    return url($path);
}

function redirect($url) {
    header('Location: ' . $url);
    exit;
}

function json($data, $statusCode = 200) {
    http_response_code($statusCode);
    header('Content-Type: application/json');
    echo json_encode($data);
    exit;
}

// ==================== AUTH HELPERS ====================
function auth_check() {
    return !empty($_SESSION['user_id']);
}

function auth_user() {
    return [
        'id' => $_SESSION['user_id'] ?? null,
        'email' => $_SESSION['user_email'] ?? null,
        'name' => $_SESSION['user_name'] ?? null,
        'tenant_id' => $_SESSION['tenant_id'] ?? null
    ];
}

function auth_id() {
    return $_SESSION['user_id'] ?? null;
}

function auth_tenant() {
    return $_SESSION['tenant_id'] ?? null;
}

function require_auth() {
    if (!auth_check()) {
        redirect(url('/login'));
    }
}

function require_guest() {
    if (auth_check()) {
        redirect(url('/app'));
    }
}

// ==================== BASE CONTROLLER ====================
class BaseController {
    protected $db;
    protected $view;
    
    public function __construct() {
        $this->db = DB::get();
        $this->view = new View();
    }
    
    protected function checkAuth() {
        require_auth();
    }
    
    protected function checkGuest() {
        require_guest();
    }
    
    protected function jsonResponse($data, $status = 200) {
        json($data, $status);
    }
    
    protected function redirect($url) {
        redirect($url);
    }
}

// ==================== INITIALIZATION ====================
// Ensure storage directories
$storagePath = dirname(__DIR__) . '/storage';
$dirs = [$storagePath, "$storagePath/uploads", "$storagePath/logs"];
foreach ($dirs as $dir) {
    if (!is_dir($dir)) mkdir($dir, 0755, true);
}

// Load configuration
Config::load();