<?php
require_once '../bootstrap/env.php';
require_once '../bootstrap/db.php';
require_once '../bootstrap/translator.php';
require_once '../app/helpers/translation.php';
require_once '../bootstrap/router.php';
require_once '../app/Models/Setting.php';

// Start session safely (avoid notice if already active)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Initialize current language
if (!isset($_SESSION['language'])) {
    $_SESSION['language'] = 'en'; // Default language
}

// Initialize router
$router = new Router();

// Define routes
$router->get('/', 'AuthController@showLogin');
$router->get('/login', 'AuthController@showLogin');
$router->post('/login', 'AuthController@login');
$router->get('/logout', 'AuthController@logout');
$router->get('/dashboard', 'UserController@dashboard');
$router->get('/users', 'UserController@index');
$router->get('/users/create', 'UserController@create');
$router->post('/users', 'UserController@store');
$router->get('/users/{id}/edit', 'UserController@edit');
$router->post('/users/{id}/update', 'UserController@update');
$router->post('/users/{id}/delete', 'UserController@delete');
$router->post('/users/{id}/restore', 'UserController@restore');

// User Types routes
$router->get('/user-types', 'UserTypeController@index');
$router->get('/user-types/create', 'UserTypeController@create');
$router->post('/user-types', 'UserTypeController@store');
$router->get('/user-types/{id}/edit', 'UserTypeController@edit');
$router->post('/user-types/{id}/update', 'UserTypeController@update');
$router->post('/user-types/{id}/delete', 'UserTypeController@delete');

// Language routes
$router->get('/languages', 'LanguageController@index');
$router->get('/languages/create', 'LanguageController@create');
$router->post('/languages', 'LanguageController@store');
$router->get('/languages/{id}/edit', 'LanguageController@edit');
$router->post('/languages/{id}/update', 'LanguageController@update');
$router->post('/languages/{id}/delete', 'LanguageController@delete');
$router->get('/languages/{id}/translations', 'LanguageController@translations');
$router->post('/languages/{id}/translations', 'LanguageController@saveTranslations');
$router->post('/switch-language', 'LanguageController@switchLanguage');

// Export / Import routes
$router->get('/export', 'ExportController@index');
$router->get('/export/languages', 'ExportController@exportLanguages');
$router->get('/export/translations', 'ExportController@exportTranslations');
$router->post('/import/languages', 'ExportController@importLanguages');
$router->post('/import/translations', 'ExportController@importTranslations');

// Reports routes (demo module)
$router->get('/reports', function() {
    require_once '../app/Views/reports/index.php';
});
$router->get('/reports/daily', 'ReportController@daily');

// Product modules
$router->get('/products', 'ProductController@index');
$router->get('/products/create', 'ProductController@create');
$router->post('/products', 'ProductController@store');
$router->get('/products/{id}/edit', 'ProductController@edit');
$router->post('/products/{id}/update', 'ProductController@update');
$router->post('/products/{id}/delete', 'ProductController@delete');
$router->post('/products/bulk-delete', 'ProductController@bulkDelete');
$router->post('/products/save-order', 'ProductController@saveOrder');
$router->post('/products/inline-update', 'ProductController@inlineUpdate');

// Product Import
$router->get('/products/import', 'ProductImportController@form');
$router->post('/products/import/preview', 'ProductImportController@preview');
$router->post('/products/import/process', 'ProductImportController@process');
// Legacy direct upload (still supported)
$router->post('/products/import', 'ProductImportController@upload');

// Categories
$router->get('/categories', 'CategoryController@index');
$router->get('/categories/create', 'CategoryController@create');
$router->post('/categories', 'CategoryController@store');
$router->get('/categories/{id}/edit', 'CategoryController@edit');
$router->post('/categories/{id}/update', 'CategoryController@update');
$router->post('/categories/{id}/delete', 'CategoryController@delete');

// Ingredients
$router->get('/ingredients', 'IngredientController@index');
$router->get('/ingredients/create', 'IngredientController@create');
$router->post('/ingredients', 'IngredientController@store');
$router->get('/ingredients/{id}/edit', 'IngredientController@edit');
$router->post('/ingredients/{id}/update', 'IngredientController@update');
$router->post('/ingredients/{id}/delete', 'IngredientController@delete');

// Units
$router->get('/units', 'UnitController@index');
$router->get('/units/create', 'UnitController@create');
$router->post('/units', 'UnitController@store');
$router->get('/units/{id}/edit', 'UnitController@edit');
$router->post('/units/{id}/update', 'UnitController@update');
$router->post('/units/{id}/delete', 'UnitController@delete');

// Report Flags
$router->get('/report-flags', 'ReportFlagController@index');
$router->get('/report-flags/create', 'ReportFlagController@create');
$router->post('/report-flags', 'ReportFlagController@store');
$router->get('/report-flags/{id}/edit', 'ReportFlagController@edit');
$router->post('/report-flags/{id}/update', 'ReportFlagController@update');
$router->post('/report-flags/{id}/delete', 'ReportFlagController@delete');

// Production Sites
$router->get('/production-sites', 'ProductionSiteController@index');
$router->get('/production-sites/create', 'ProductionSiteController@create');
$router->post('/production-sites', 'ProductionSiteController@store');
$router->get('/production-sites/{id}/edit', 'ProductionSiteController@edit');
$router->post('/production-sites/{id}/update', 'ProductionSiteController@update');
$router->post('/production-sites/{id}/delete', 'ProductionSiteController@delete');

// Customers / Receivers
$router->get('/customers', 'CustomerController@index');
$router->get('/customers/create', 'CustomerController@create');
$router->post('/customers', 'CustomerController@store');
$router->get('/customers/{id}/edit', 'CustomerController@edit');
$router->post('/customers/{id}/update', 'CustomerController@update');
$router->post('/customers/{id}/delete', 'CustomerController@delete');

// Orders
$router->get('/orders', 'OrderController@index');
$router->get('/orders/create', 'OrderController@create');
$router->get('/orders/panel', 'OrderController@panel');
$router->post('/orders', 'OrderController@store');
$router->get('/orders/{id}', 'OrderController@show');
$router->get('/orders/{id}/edit', 'OrderController@edit');
$router->post('/orders/{id}/update', 'OrderController@update');
$router->post('/orders/{id}/delete', 'OrderController@delete');

// Settings routes
$router->get('/settings', 'SettingController@index');
$router->post('/settings/save', 'SettingController@save');

// Stock & Storage
$router->get('/stock/ingredients', 'StockController@ingredients');
$router->post('/stock/apply-daily', 'StockController@applyDaily');
$router->get('/stock/usage-history', 'StockController@usageHistory');
$router->post('/stock/rollback-daily', 'StockController@rollbackDaily'); // new behavior: delete + restore
$router->get('/stock/usage-chart', 'StockController@usageChart');
$router->get('/stock/daily-usage', 'StockController@dailyUsage');
$router->post('/stock/apply-usage-single', 'StockController@applyUsageSingle');
$router->post('/stock/apply-usage-all', 'StockController@applyUsageAll');
$router->get('/stock/daily-usage', 'StockController@dailyUsage');

// Ingredient storage adjustments
$router->post('/storage/adjust', 'IngredientStorageController@adjust');
$router->post('/storage/merge-rollback', 'IngredientStorageController@mergeRollback');

// Restocks
$router->get('/restocks', 'RestockController@index');
$router->get('/restocks/create', 'RestockController@create');
$router->post('/restocks', 'RestockController@store');
// Newly added detail & maintenance routes
$router->get('/restocks/{id}', 'RestockController@show');
$router->get('/restocks/{id}/edit', 'RestockController@edit');
$router->post('/restocks/{id}/update', 'RestockController@update');
$router->post('/restocks/{id}/delete', 'RestockController@delete');

// Maintenance mode check (allow login/logout and admins)
$settingModel = new Setting();
$maintenance = $settingModel->get('maintenance_mode', '0') === '1';
if ($maintenance) {
    $allowed = ['/login','/logout'];
    $uriPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $isAdmin = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin';
    if (!$isAdmin && !in_array(str_replace(['/samanta_crm','/samanta_crm/public'], '', $uriPath), $allowed)) {
        http_response_code(503);
        $msg = $settingModel->get('maintenance_message', 'Maintenance in progress.');
        echo "<html><head><title>Maintenance</title><link href='https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css' rel='stylesheet'></head><body class='d-flex align-items-center' style='min-height:100vh'><div class='container'><div class='row justify-content-center'><div class='col-md-6'><div class='card shadow'><div class='card-body text-center'><h1 class='h3 mb-3'><i class='fas fa-tools me-2'></i>Maintenance</h1><p>" . htmlspecialchars($msg) . "</p></div></div></div></div></div></body></html>";
        exit;
    }
}

// Handle the request
$router->dispatch($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
