<?php
/**
 * TellerPro — Main Entry Point
 * Handles: public pages + tenant app
 */

require_once __DIR__ . '/config/config.php';

// Check for installation
if (!file_exists(__DIR__ . '/.env') && file_exists(__DIR__ . '/install.php')) {
    header("Location: install.php");
    exit;
}

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/core/Security.php';
require_once __DIR__ . '/core/SecurityHeaders.php';
require_once __DIR__ . '/core/Auth.php';
require_once __DIR__ . '/core/SuperAuth.php';
require_once __DIR__ . '/core/PlanGuard.php';
require_once __DIR__ . '/core/Model.php';
require_once __DIR__ . '/core/Router.php';
require_once __DIR__ . '/core/Paystack.php';
require_once __DIR__ . '/core/helpers.php';

// Load concurrency optimizations
require_once __DIR__ . '/bootstrap/optimizations.php';

// Initialize concurrency optimizations
initConcurrencyOptimizations();

// Set security headers
SecurityHeaders::set();

// Auto-load models & controllers
spl_autoload_register(function(string $class) {
    $paths = [
        __DIR__ . '/models/' . $class . '.php',
        __DIR__ . '/controllers/public/' . $class . '.php',
        __DIR__ . '/controllers/tenant/' . $class . '.php',
        __DIR__ . '/controllers/superadmin/' . $class . '.php',
    ];
    foreach ($paths as $path) {
        if (file_exists($path)) { require_once $path; return; }
    }
});

// Get request URI relative to app root
$uri    = $_SERVER['REQUEST_URI'] ?? '/';
$script = $_SERVER['SCRIPT_NAME'] ?? '/index.php';
$base   = str_replace('\\', '/', dirname($script));
if ($base === '/') $base = '';

// Start session - Separate context for Super Admin and Regular App
if (str_starts_with(strtolower($uri), strtolower($base . '/superadmin'))) {
    SuperAuth::startSession();
} else {
    Auth::startSession();
}

$temp_uri = $uri;
// Remove base path from URI
if ($base && str_starts_with(strtolower($uri), strtolower($base))) {
    $temp_uri = substr($uri, strlen($base));
}
$uri    = strtok($temp_uri, '?') ?: '/';
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

$router = new Router();

// ── Public Routes ────────────────────────────────────────────
$router->get('/',                  [PublicController::class, 'landing']);
$router->get('/login',             [AuthController::class,   'showLogin']);
$router->post('/login',            [AuthController::class,   'login']);
$router->get('/register',          [AuthController::class,   'showRegister']);
$router->post('/register',         [AuthController::class,   'register']);
$router->get('/logout',            [AuthController::class,   'logout']);
$router->get('/pricing',           [PublicController::class, 'pricing']);

// Onboarding
$router->get('/onboarding/business',  [OnboardingController::class, 'showBusiness']);
$router->post('/onboarding/business', [OnboardingController::class, 'saveBusiness']);
$router->get('/onboarding/plan',      [OnboardingController::class, 'showPlan']);
$router->post('/onboarding/plan',     [OnboardingController::class, 'selectPlan']);
$router->get('/onboarding/done',      [OnboardingController::class, 'done']);

// ── Tenant App Routes ─────────────────────────────────────────
$router->get('/dashboard',         [DashboardController::class, 'index']);

// Products
$router->get('/products',            [ProductController::class, 'index']);
$router->get('/products/create',     [ProductController::class, 'create']);
$router->post('/products/create',    [ProductController::class, 'store']);
$router->post('/products/import',    [ProductController::class, 'import']);
$router->get('/products/import-template', [ProductController::class, 'importTemplate']);
$router->post('/products/stock-import', [ProductController::class, 'stockImport']);
$router->get('/products/stock-import-template', [ProductController::class, 'stockImportTemplate']);
$router->get('/products/{id}',       [ProductController::class, 'show']);
$router->get('/products/{id}/history',[ProductController::class, 'history']);
$router->get('/products/{id}/edit',  [ProductController::class, 'edit']);
$router->post('/products/{id}/edit', [ProductController::class, 'update']);
$router->post('/products/{id}/delete',[ProductController::class, 'destroy']);

// Inventory
$router->get('/inventory',             [InventoryController::class, 'index']);
$router->get('/inventory/adjust',      [InventoryController::class, 'adjust']);
$router->post('/inventory/adjust',     [InventoryController::class, 'adjust']);
$router->get('/inventory/adjustment-list', [InventoryController::class, 'adjustmentList']);
$router->get('/inventory/transfer',    [InventoryController::class, 'transfer']);
$router->post('/inventory/transfer',   [InventoryController::class, 'transfer']);
$router->get('/inventory/reconcile',   [InventoryController::class, 'reconcile']);
$router->post('/inventory/reconcile-fix', [InventoryController::class, 'reconcileFix']);
$router->get('/api/stock-info',         function() { include APP_ROOT . '/api/index.php'; });
$router->get('/api/recent-sale',        function() { include APP_ROOT . '/api/index.php'; });
$router->post('/inventory/locations',  [InventoryController::class, 'storeLocation']);

// Sales - POS
$router->get('/sales',                [SalesController::class, 'index']);
$router->get('/sales/export',         [SalesController::class, 'export']);
$router->get('/sales/create',         [InvoiceController::class, 'create']);
$router->get('/invoices/create',      [InvoiceController::class, 'create']);
$router->post('/invoices/store',      [InvoiceController::class, 'store']);
$router->get('/sales/pos',            [PosController::class, 'index']);
$router->get('/sales/pos/products',   [PosController::class, 'searchProducts']);
$router->post('/sales/pos/store',     [PosController::class, 'store']);
$router->post('/sales/pos/suspend',   [PosController::class, 'suspend']);
$router->get('/sales/pos/resume/{id}', [PosController::class, 'resume']);
$router->get('/sales/pos/recent',     [PosController::class, 'recentTransactions']);
$router->get('/sales/pos/suspended',  [PosController::class, 'suspendedOrders']);
$router->get('/sales/{id}/pos-receipt/{format}', [SalesController::class, 'printReceipt']);
$router->get('/sales/{id}/print/{format}', [InvoiceController::class, 'print']);
$router->get('/sales/{id}',           [SalesController::class, 'show']);
$router->get('/sales/{id}/edit',      [SalesController::class, 'edit']);
$router->post('/sales/{id}/update',   [SalesController::class, 'update']);
$router->get('/sales/{id}/pay',       [SalesController::class, 'pay']);
$router->post('/sales/{id}/process-payment', [SalesController::class, 'processPayment']);
$router->get('/sales/{id}/delete',    [SalesController::class, 'delete']);

// Purchases
$router->get('/purchases',              [PurchaseController::class, 'index']);
$router->get('/purchases/create',       [PurchaseController::class, 'create']);
$router->post('/purchases/create',      [PurchaseController::class, 'store']);
$router->get('/purchases/{id}',         [PurchaseController::class, 'show']);
$router->get('/purchases/{id}/edit',    [PurchaseController::class, 'edit']);
$router->post('/purchases/{id}/update', [PurchaseController::class, 'update']);
$router->get('/purchases/{id}/delete',  [PurchaseController::class, 'delete']);
$router->get('/purchases/{id}/pay',     [PurchaseController::class, 'pay']);
$router->post('/purchases/{id}/process-payment', [PurchaseController::class, 'processPayment']);
$router->post('/purchases/process-payment-modal', [PurchaseController::class, 'processPaymentFromModal']);

// Customers
$router->get('/customers',             [ContactController::class, 'customers']);
$router->post('/customers/store',       [ContactController::class, 'storeCustomer']);
$router->post('/customers/{id}/update', [ContactController::class, 'updateCustomer']);
$router->post('/customers/{id}/delete',[ContactController::class, 'deleteCustomer']);

// Customer Ledger
$router->get('/customer-ledger',       [CustomerLedgerController::class, 'index']);
$router->get('/customer-ledger/{id}',  [CustomerLedgerController::class, 'show']);
$router->get('/customer-ledger/{id}/print/{format}', [CustomerLedgerController::class, 'print']);
$router->post('/customer-ledger/store', [CustomerLedgerController::class, 'store']);
$router->post('/customer-ledger/opening-balance', [CustomerLedgerController::class, 'addOpeningBalance']);

// Tax Groups
$router->get('/tax',                   [TaxController::class, 'index']);
$router->get('/tax/create',            [TaxController::class, 'create']);
$router->post('/tax/store',            [TaxController::class, 'store']);
$router->get('/tax/{id}/edit',         [TaxController::class, 'edit']);
$router->post('/tax/{id}/update',      [TaxController::class, 'update']);
$router->post('/tax/{id}/delete',      [TaxController::class, 'destroy']);

// Suppliers
$router->get('/suppliers',             [ContactController::class, 'suppliers']);
$router->post('/suppliers/store',       [ContactController::class, 'storeSupplier']);
$router->post('/suppliers/{id}/update', [ContactController::class, 'updateSupplier']);

// Supplier Ledger
$router->get('/supplier-ledger',       [SupplierLedgerController::class, 'index']);
$router->get('/supplier-ledger/{id}',  [SupplierLedgerController::class, 'show']);
$router->get('/supplier-ledger/{id}/print/{format}', [SupplierLedgerController::class, 'print']);
$router->post('/supplier-ledger/store', [SupplierLedgerController::class, 'store']);
$router->post('/supplier-ledger/opening-balance', [SupplierLedgerController::class, 'addOpeningBalance']);

// Users
$router->get('/users',               [UserController::class, 'index']);
$router->get('/users/create',        [UserController::class, 'create']);
$router->post('/users/create',       [UserController::class, 'store']);
$router->get('/users/{id}/edit',     [UserController::class, 'edit']);
$router->post('/users/{id}/edit',    [UserController::class, 'update']);
$router->post('/users/{id}/delete',  [UserController::class, 'destroy']);

// Roles
$router->get('/roles',               [RolesController::class, 'index']);
$router->get('/roles/create',        [RolesController::class, 'create']);
$router->post('/roles/store',        [RolesController::class, 'store']);
$router->get('/roles/{id}/edit',     [RolesController::class, 'edit']);
$router->post('/roles/{id}/update',  [RolesController::class, 'update']);
$router->post('/roles/{id}/delete',  [RolesController::class, 'delete']);

// Reports
$router->get('/reports',             [ReportsController::class, 'index']);

// Settings
$router->get('/settings',            [SettingsController::class, 'index']);
$router->post('/settings/business',      [SettingsController::class, 'updateBusiness']);
$router->post('/settings/preferences',   [SettingsController::class, 'updatePreferences']);
$router->post('/settings/reset',         [SettingsController::class, 'factoryReset']);

// Categories
$router->get('/settings/categories',     [SettingsController::class, 'categories']);
$router->post('/settings/store-category', [SettingsController::class, 'storeCategory']);
$router->post('/settings/update-category',[SettingsController::class, 'updateCategory']);
$router->post('/settings/delete-category',[SettingsController::class, 'deleteCategory']);

// Units
$router->get('/settings/units',          [SettingsController::class, 'units']);
$router->post('/settings/store-unit',     [SettingsController::class, 'storeUnit']);
$router->post('/settings/update-unit',    [SettingsController::class, 'updateUnit']);
$router->post('/settings/delete-unit',    [SettingsController::class, 'deleteUnit']);
$router->post('/settings/toggle-unit-status',[SettingsController::class, 'toggleUnitStatus']);

// Brands
$router->get('/settings/brands',         [SettingsController::class, 'brands']);
$router->post('/settings/store-brand',    [SettingsController::class, 'storeBrand']);
$router->post('/settings/update-brand',   [SettingsController::class, 'updateBrand']);
$router->post('/settings/delete-brand',   [SettingsController::class, 'deleteBrand']);

// Batch & Expiry
$router->get('/settings/batch-expiry',   [SettingsController::class, 'batchExpiry']);
$router->post('/settings/update-batch-tracking',[SettingsController::class, 'updateBatchTracking']);
$router->post('/settings/delete-batch',   [SettingsController::class, 'deleteBatch']);

// Locations (Warehouses/Shops)
$router->get('/settings/locations',          [SettingsController::class, 'locations']);
$router->post('/settings/store-location',     [SettingsController::class, 'storeLocation']);
$router->post('/settings/update-location',    [SettingsController::class, 'updateLocation']);
$router->post('/settings/delete-location',    [SettingsController::class, 'deleteLocation']);
$router->post('/settings/toggle-location-status',[SettingsController::class, 'toggleLocationStatus']);
$router->post('/settings/set-default-location',[SettingsController::class, 'setDefaultLocation']);

// Payment Methods
$router->get('/settings/payment-methods',    [SettingsController::class, 'paymentMethods']);
$router->post('/settings/payment-methods/save',[SettingsController::class, 'savePaymentMethods']);

// Billing
$router->get('/billing',               [BillingController::class, 'index']);
$router->post('/billing/upgrade',      [BillingController::class, 'upgrade']);
$router->post('/billing/cancel',       [BillingController::class, 'cancel']);

$router->post('/billing/webhook',    [BillingController::class, 'webhook']);
$router->post('/billing/download-invoice', [BillingController::class, 'downloadInvoice']);

// Notifications
$router->get('/notifications',            [NotificationController::class, 'index']);
$router->post('/notifications/mark-read', [NotificationController::class, 'markRead']);
$router->post('/notifications/mark-all-read', [NotificationController::class, 'markAllRead']);
$router->post('/notifications/create', [NotificationController::class, 'create']);
$router->post('/notifications/delete', [NotificationController::class, 'delete']);
$router->post('/notifications/clean', [NotificationController::class, 'cleanup']);

// Batch Management
$router->get('/batches',               [BatchController::class, 'index']);
$router->get('/batches/create',           [BatchController::class, 'create']);
$router->get('/batches/edit/{id}',         [BatchController::class, 'edit']);
$router->post('/batches/create',          [BatchController::class, 'create']);
$router->post('/batches/update',          [BatchController::class, 'update']);
$router->post('/batches/delete',          [BatchController::class, 'delete']);

// Stock Taking
$router->get('/stock-takings',               [StockTakingController::class, 'index']);
$router->get('/stock-takings/create',       [StockTakingController::class, 'create']);
$router->post('/stock-takings/start',       [StockTakingController::class, 'start']);
$router->get('/stock-takings/count/{id}',   [StockTakingController::class, 'count']);
$router->post('/stock-takings/save',        [StockTakingController::class, 'save']);
$router->get('/stock-takings/report/{id}',  [StockTakingController::class, 'report']);
$router->get('/stock-takings/view/{id}',    [StockTakingController::class, 'view']);
$router->post('/stock-takings/delete',      [StockTakingController::class, 'delete']);
$router->post('/stock-takings/update-stock', [StockTakingController::class, 'updateStock']);

// ── API (AJAX) ────────────────────────────────────────────────
$router->get('/api/products/search',    [ApiController::class, 'searchProducts']);
$router->get('/api/products/{id}/stock',[ApiController::class, 'productStock']);
$router->get('/api/location-stock',     [ApiController::class, 'locationProductsStock']);
$router->get('/api/customers/search',   [ApiController::class, 'searchCustomers']);
$router->get('/api/suppliers/search',   [ApiController::class, 'searchSuppliers']);
$router->get('/api/notifications',      [ApiController::class, 'notifications']);
$router->get('/api/dashboard/stats',    [ApiController::class, 'dashboardStats']);

// ── Super Admin Routes ──────────────────────────────────────────
$router->get('/superadmin/login',              [SAAuthController::class, 'showLogin']);
$router->post('/superadmin/login',             [SAAuthController::class, 'login']);
$router->get('/superadmin/logout',             [SAAuthController::class, 'logout']);
$router->get('/superadmin/reset-password',     [SAAuthController::class, 'showPasswordReset']);
$router->post('/superadmin/reset-password',    [SAAuthController::class, 'resetPassword']);
$router->post('/superadmin/system-reset',      [SAAuthController::class, 'systemReset']);
$router->get('/superadmin',                    [SADashboardController::class, 'index']);
$router->get('/superadmin/tenants',            [SATenantsController::class, 'index']);
$router->get('/superadmin/tenants/{id}',       [SATenantsController::class, 'show']);
$router->post('/superadmin/tenants/{id}/delete', [SATenantsController::class, 'destroy']);
$router->post('/superadmin/tenants/{id}/suspend', [SATenantsController::class, 'suspend']);
$router->post('/superadmin/tenants/{id}/activate', [SATenantsController::class, 'activate']);
$router->post('/superadmin/tenants/{id}/login-as-admin', [SATenantsController::class, 'loginAsAdmin']);
$router->post('/superadmin/tenants/{id}/reset-password', [SATenantsController::class, 'resetPassword']);
$router->get('/superadmin/plans',              [SAPlansController::class, 'index']);
$router->get('/superadmin/plans/create',       [SAPlansController::class, 'create']);
$router->post('/superadmin/plans/create',      [SAPlansController::class, 'store']);
$router->get('/superadmin/plans/{id}/edit',    [SAPlansController::class, 'edit']);
$router->post('/superadmin/plans/{id}/update', [SAPlansController::class, 'update']);
$router->post('/superadmin/plans/{id}/delete', [SAPlansController::class, 'destroy']);
$router->get('/superadmin/subscriptions',      [SASubscriptionsController::class, 'index']);
$router->get('/superadmin/paystack',            [SAPaystackController::class, 'index']);
$router->post('/superadmin/paystack/webhook',  [SAPaystackController::class, 'webhook']);

// Dispatch
$router->dispatch($uri, $method);
