<?php
require_once '../bootstrap/env.php';
require_once '../bootstrap/db.php';
require_once '../bootstrap/translator.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');
$router->get('/reports/daily/production-sites', 'ReportController@dailyProductionSites');
$router->get('/reports/daily/ingredients', 'ReportController@dailyIngredients');
$router->get('/stock/ingredients', 'StockController@ingredients');
$router->post('/stock/applyDaily', 'StockController@applyDaily');
$router->get('/stock/usage-history', 'StockController@usageHistory');
$router->get('/stock/usage-chart', 'StockController@usageChart');
$router->post('/stock/rollbackDaily', 'StockController@rollbackDaily');

// 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');
// Ingredient Storage
$router->get('/ingredient-storage', 'IngredientStorageController@index');
$router->post('/ingredient-storage/save', 'IngredientStorageController@save');
$router->post('/ingredient-storage/{id}/delete', 'IngredientStorageController@delete');
$router->post('/ingredient-storage/merge-rollback', 'IngredientStorageController@mergeRollback');

// Restocks
$router->get('/restocks', 'RestockController@index');
$router->get('/restocks/create', 'RestockController@create');
$router->post('/restocks', 'RestockController@store');
$router->get('/restocks/{id}/edit', 'RestockController@edit');
$router->get('/restocks/{id}', 'RestockController@show');
$router->post('/restocks/{id}/update', 'RestockController@update');
$router->post('/restocks/{id}/delete', 'RestockController@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->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');
$router->get('/api/dashboard-metrics', function(){
    header('Content-Type: application/json');
    $pdo=$GLOBALS['pdo'];
    $today=date('Y-m-d');
    // applied days count
    $appliedDays=(int)$pdo->query("SELECT COUNT(DISTINCT apply_date) FROM ingredient_usage_applied")->fetchColumn();
    // pending usage today (orders usage - applied usage today)
    $sqlUsage="SELECT COALESCE(SUM(pi.quantity*oi.quantity),0) FROM order_items oi JOIN products p ON p.id=oi.product_id JOIN product_ingredients pi ON pi.product_id=p.id JOIN orders o ON o.id=oi.order_id WHERE DATE(o.order_date)='{$today}'";
    $ordersUsage=(float)$pdo->query($sqlUsage)->fetchColumn();
    $appliedToday=(float)$pdo->query("SELECT COALESCE(SUM(applied_qty),0) FROM ingredient_usage_applied WHERE apply_date='{$today}'")->fetchColumn();
    $pendingToday=max(0,$ordersUsage-$appliedToday);
    // low stock (remaining < 0 or stock < some threshold relative to applied) simplistic threshold < 1
    // detect correct movement column name
    $colCheckCols = [];
    try { $colCheckCols = $pdo->query("SHOW COLUMNS FROM ingredient_storage")->fetchAll(PDO::FETCH_COLUMN); } catch(Exception $e){ $colCheckCols=[]; }
    $moveCol = in_array('change_qty',$colCheckCols,true)?'change_qty':(in_array('quantity',$colCheckCols,true)?'quantity':'change_qty');
    $lowStock=(int)$pdo->query("SELECT COUNT(*) FROM (SELECT ingredient_id,SUM($moveCol) q FROM ingredient_storage GROUP BY ingredient_id HAVING q<1) t")->fetchColumn();
    // mini chart last 14 days: build arrays for one popular ingredient (top by usage) or aggregated
    $labels=[];$applied=[];$stock=[];
    $start=date('Y-m-d',strtotime('-13 days'));
    // aggregate restocks & applied to get stock trajectory (starting from 0 baseline)
    $restocksStmt=$pdo->prepare("SELECT r.restock_date d, SUM(ri.quantity) q FROM restock_items ri JOIN restocks r ON r.id=ri.restock_id WHERE r.restock_date BETWEEN ? AND ? GROUP BY r.restock_date");
    $restocksStmt->execute([$start,$today]); $rest=[]; while($r=$restocksStmt->fetch(PDO::FETCH_ASSOC)){ $rest[$r['d']]=$r['q']; }
    $appliedStmt=$pdo->prepare("SELECT apply_date d, SUM(applied_qty) q FROM ingredient_usage_applied WHERE apply_date BETWEEN ? AND ? GROUP BY apply_date");
    $appliedStmt->execute([$start,$today]); $app=[]; while($r=$appliedStmt->fetch(PDO::FETCH_ASSOC)){ $app[$r['d']]=$r['q']; }
    $running=0; $d=$start; while($d <= $today){ $running += ($rest[$d]??0); $running -= ($app[$d]??0); $labels[]=$d; $applied[]=(float)($app[$d]??0); $stock[]=$running; $d=date('Y-m-d',strtotime($d.' +1 day')); }
    echo json_encode(['applied_days'=>$appliedDays,'pending_usage_today'=>$pendingToday,'low_stock'=>$lowStock,'chart'=>['labels'=>$labels,'applied'=>$applied,'stock'=>$stock]]);
});

// Demo Data
$router->get('/demo-data', 'DemoDataController@form');
$router->post('/demo-data/generate', 'DemoDataController@generate');

// 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']);
