<?php
require_once '../bootstrap/env.php';
require_once '../bootstrap/db.php';
require_once '../bootstrap/translator.php';
require_once '../app/helpers/translation.php';
require_once '../app/helpers/url.php';
require_once '../app/helpers/UnitHelper.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'] = 'pl'; // 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->get('/languages/{id}/export', 'LanguageController@exportTranslations');
$router->post('/languages/{id}/import', 'LanguageController@importTranslations');
$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() {
    if(!isset($_SESSION['user_id'])){ redirect('login'); exit; }
    $title = __('reports.title', 'Reports');
    ob_start();
    require_once '../app/Views/reports/index.php';
    $content = ob_get_clean();
    require_once '../app/Views/layout.php';
});
$router->get('/reports/daily', 'ReportController@daily');

// Product modules
$router->get('/products', 'ProductController@index');
$router->get('/products/get-products', 'ProductController@getProducts');
$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/delete-all', 'ProductController@deleteAll');
$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->post('/categories/reorder', 'CategoryController@reorder');
$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');
$router->get('/ingredients/{id}/product-links', 'IngredientController@getProductLinks');
$router->post('/ingredients/{id}/link-products', 'IngredientController@linkProducts');
$router->post('/ingredients/{id}/unlink-product', 'IngredientController@unlinkProduct');
$router->post('/ingredients/{id}/update-link-quantity', 'IngredientController@updateLinkQuantity');

// 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/latest', 'OrderController@getLatest');
$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');
$router->post('/orders/delete-all', 'OrderController@deleteAll');

// Cake Features routes
$router->get('/cake-features', 'CakeFeaturesController@index');
$router->post('/cake-features/flavor/create', 'CakeFeaturesController@createFlavor');
$router->post('/cake-features/flavor/{id}/update', 'CakeFeaturesController@updateFlavor');
$router->post('/cake-features/flavor/{id}/delete', 'CakeFeaturesController@deleteFlavor');
$router->post('/cake-features/size/create', 'CakeFeaturesController@createSize');
$router->post('/cake-features/size/{id}/update', 'CakeFeaturesController@updateSize');
$router->post('/cake-features/size/{id}/delete', 'CakeFeaturesController@deleteSize');
$router->post('/cake-features/type/create', 'CakeFeaturesController@createType');
$router->post('/cake-features/type/{id}/update', 'CakeFeaturesController@updateType');
$router->post('/cake-features/type/{id}/delete', 'CakeFeaturesController@deleteType');
$router->post('/cake-features/location/create', 'CakeFeaturesController@createLocation');
$router->post('/cake-features/location/{id}/update', 'CakeFeaturesController@updateLocation');
$router->post('/cake-features/location/{id}/delete', 'CakeFeaturesController@deleteLocation');
$router->post('/cake-features/pricing/update', 'CakeFeaturesController@updatePricing');

// Public Cake Order Form
$router->get('/cake-order', 'CakeOrderController@publicForm');
$router->post('/cake-order/submit', 'CakeOrderController@submit');

// Admin Cake Orders Management
$router->get('/cake-orders', 'CakeOrderController@index');
$router->get('/cake-orders/create', 'CakeOrderController@create');
$router->post('/cake-orders/create', 'CakeOrderController@create');
$router->get('/cake-orders/{id}', 'CakeOrderController@view');
$router->get('/cake-orders/edit/{id}', 'CakeOrderController@edit');
$router->post('/cake-orders/edit/{id}', 'CakeOrderController@edit');
$router->get('/cake-orders/delete/{id}', 'CakeOrderController@delete');

// API routes
$router->post('/api/upload-image', 'ApiController@uploadImage');

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

// Migration routes (Gravity Forms to new system)
$router->get('/migration', 'MigrationController@index');
$router->get('/migration/cake-orders', 'MigrationController@cakeOrdersForm');
$router->get('/migration/regular-orders', 'MigrationController@regularOrdersForm');
$router->get('/migration/products', 'MigrationController@showProductsMigration');
$router->post('/migration/preview-orders', 'MigrationController@previewOrders');
$router->post('/migration/preview-products', 'MigrationController@previewProducts');
$router->post('/migration/import-cake-orders', 'MigrationController@importCakeOrders');
$router->post('/migration/import-orders', 'MigrationController@importOrders');
$router->post('/migration/import-products', 'MigrationController@importProducts');
$router->get('/migration/download-report', 'MigrationController@downloadReport');

// Menu Management (Stationary Locations)
$router->get('/menu/items', 'MenuController@items');
$router->get('/menu/items/create', 'MenuController@createItem');
$router->post('/menu/items/store', 'MenuController@storeItem');
$router->post('/menu/items/reorder', 'MenuController@reorderItems');
$router->post('/menu/items/toggle-location', 'MenuController@toggleLocation');
$router->get('/menu/preview/{id}', 'MenuController@preview');
$router->get('/menu/items/{id}/edit', 'MenuController@editItem');
$router->post('/menu/items/{id}/update', 'MenuController@updateItem');
$router->post('/menu/items/{id}/delete', 'MenuController@deleteItem');
$router->get('/menu/locations', 'MenuController@locations');
$router->post('/menu/locations/store', 'MenuController@storeLocation');
$router->post('/menu/locations/{id}/update', 'MenuController@updateLocation');
$router->post('/menu/locations/{id}/delete', 'MenuController@deleteLocation');

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

// Menu Versions (Snapshots)
$router->get('/menu/versions', 'MenuVersionController@index');
$router->post('/menu/versions/create', 'MenuVersionController@create');
$router->get('/menu/versions/download', 'MenuVersionController@download');
$router->get('/menu/versions/download-viewer', 'MenuVersionController@downloadViewer');
$router->post('/menu/versions/delete', 'MenuVersionController@delete');

// 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;
    }
}

// Get request URI
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';

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

