<?php
/**
 * WhatsApp CRM - Front Controller & Application Bootstrap
 */

declare(strict_types=1);

// 1. PSR-4 Autoloader
spl_autoload_register(function ($class) {
    $prefix = 'App\\';
    $baseDir = dirname(__DIR__) . '/app/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relativeClass = substr($class, $len);
    $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';

    if (file_exists($file)) {
        require $file;
    }
});

// 2. Start Session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// 3. Load App Configuration
use App\Config\Config;
use App\Core\Router;
use App\Core\Request;
use App\Core\Middleware;
use App\Controllers\AuthController;
use App\Controllers\DashboardController;
use App\Controllers\ChatController;
use App\Controllers\ContactsController;
use App\Controllers\PipelineController;
use App\Controllers\AutomationController;
use App\Controllers\CampaignController;
use App\Controllers\TemplateController;
use App\Controllers\WebhookController;
use App\Controllers\SettingsController;
use App\Controllers\UsersController;

Config::load();

$timezone = Config::get('TIMEZONE', 'Asia/Kolkata');
date_default_timezone_set($timezone);

// 4. Define Routes

// Webhook Routes (Public for Meta Graph API)
Router::get('/webhook', [WebhookController::class, 'handle']);
Router::post('/webhook', [WebhookController::class, 'handle']);

// Auth Routes
Router::get('/login', [AuthController::class, 'showLogin']);
Router::post('/login', [AuthController::class, 'login']);
Router::get('/logout', [AuthController::class, 'logout']);
Router::get('/profile', [AuthController::class, 'profile'], [[Middleware::class, 'requireAuth']]);
Router::post('/profile/update', [AuthController::class, 'updateProfile'], [[Middleware::class, 'requireAuth']]);

// Dashboard
Router::get('/', [DashboardController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::get('/dashboard', [DashboardController::class, 'index'], [[Middleware::class, 'requireAuth']]);

// Live Chat Inbox
Router::get('/chat', [ChatController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::get('/api/chat/inbox', [ChatController::class, 'getInbox'], [[Middleware::class, 'requireAuth']]);
Router::get('/api/chat/conversation/{id}', [ChatController::class, 'getConversationData'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/send', [ChatController::class, 'sendMessage'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/send-template', [ChatController::class, 'sendTemplate'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/read/{id}', [ChatController::class, 'markRead'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/assign', [ChatController::class, 'assignAgent'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/status', [ChatController::class, 'changeStatus'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/chat/upload', [ChatController::class, 'uploadMedia'], [[Middleware::class, 'requireAuth']]);

// Contacts & Leads
Router::get('/contacts', [ContactsController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::get('/contacts/{id}', [ContactsController::class, 'view'], [[Middleware::class, 'requireAuth']]);
Router::post('/contacts', [ContactsController::class, 'store'], [[Middleware::class, 'requireAuth']]);
Router::post('/contacts/{id}/update', [ContactsController::class, 'update'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/contacts/{id}/update', [ContactsController::class, 'update'], [[Middleware::class, 'requireAuth']]);
Router::post('/contacts/{id}/delete', [ContactsController::class, 'delete'], [[Middleware::class, 'requireAuth']]);
Router::post('/contacts/import', [ContactsController::class, 'importCsv'], [[Middleware::class, 'requireAuth']]);
Router::get('/contacts/export', [ContactsController::class, 'exportCsv'], [[Middleware::class, 'requireAuth']]);

// Sales Pipeline & Deals
Router::get('/pipeline', [PipelineController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/deals/create', [PipelineController::class, 'store'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/deals/move', [PipelineController::class, 'moveStage'], [[Middleware::class, 'requireAuth']]);
Router::post('/deals/{id}/delete', [PipelineController::class, 'delete'], [[Middleware::class, 'requireAuth']]);

// Automations & Chatbots
Router::get('/automations', [AutomationController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::post('/automations', [AutomationController::class, 'store'], [[Middleware::class, 'requireAuth']]);
Router::post('/automations/{id}/toggle', [AutomationController::class, 'toggle'], [[Middleware::class, 'requireAuth']]);
Router::post('/automations/{id}/delete', [AutomationController::class, 'delete'], [[Middleware::class, 'requireAuth']]);
Router::post('/automations/working-hours', [AutomationController::class, 'saveWorkingHours'], [[Middleware::class, 'requireAuth']]);

// Broadcast Campaigns
Router::get('/campaigns', [CampaignController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::get('/campaigns/create', [CampaignController::class, 'create'], [[Middleware::class, 'requireAuth']]);
Router::post('/campaigns', [CampaignController::class, 'store'], [[Middleware::class, 'requireAuth']]);
Router::get('/api/campaigns/{id}/logs', [CampaignController::class, 'logs'], [[Middleware::class, 'requireAuth']]);

// Templates
Router::get('/templates', [TemplateController::class, 'index'], [[Middleware::class, 'requireAuth']]);
Router::post('/templates', [TemplateController::class, 'store'], [[Middleware::class, 'requireAuth']]);
Router::post('/templates/{id}/delete', [TemplateController::class, 'delete'], [[Middleware::class, 'requireAuth']]);

// Settings & Local Simulator
Router::get('/settings', [SettingsController::class, 'index'], [[Middleware::class, 'requireAdmin']]);
Router::post('/settings', [SettingsController::class, 'update'], [[Middleware::class, 'requireAdmin']]);
Router::get('/api/settings/local-qr-status', [SettingsController::class, 'getLocalQrStatus'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/settings/local-qr-logout', [SettingsController::class, 'logoutLocalQr'], [[Middleware::class, 'requireAuth']]);
Router::get('/settings/simulator', [SettingsController::class, 'simulator'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/settings/simulator/incoming', [SettingsController::class, 'simulateIncomingMessage'], [[Middleware::class, 'requireAuth']]);
Router::post('/api/settings/simulator/status', [SettingsController::class, 'simulateStatusUpdate'], [[Middleware::class, 'requireAuth']]);

// Users & Team Management
Router::get('/users', [UsersController::class, 'index'], [[Middleware::class, 'requireAdmin']]);
Router::post('/users', [UsersController::class, 'store'], [[Middleware::class, 'requireAdmin']]);
Router::post('/users/{id}/update', [UsersController::class, 'update'], [[Middleware::class, 'requireAdmin']]);
Router::post('/users/{id}/delete', [UsersController::class, 'delete'], [[Middleware::class, 'requireAdmin']]);

// 5. Dispatch Current Request
$method = Request::getMethod();
$uri = Request::getUri();

Router::dispatch($method, $uri);
