<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\MenuController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\PaymentController;
use App\Http\Controllers\KitchenController;
use App\Http\Controllers\InventoryController;
use App\Http\Controllers\ReportsController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\TableController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\WaiterController;
use App\Http\Controllers\ExpenseController;
use App\Http\Controllers\PettyCashController;
use App\Http\Controllers\SettingsController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
*/

// Global OPTIONS handler for CORS preflight
Route::options('{any}', function () {
    return response()->json([], 200, [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS, PATCH',
        'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, Accept',
        'Access-Control-Max-Age' => '86400',
    ]);
})->where('any', '.*');

// Public routes
Route::options('/auth/login', [AuthController::class, 'options']);
Route::post('/auth/login', [AuthController::class, 'login']);
Route::post('/auth/login-pin', [AuthController::class, 'loginWithPin']);
Route::post('/auth/register', [AuthController::class, 'register']);

// Protected routes
Route::middleware('auth:sanctum')->group(function () {
    // Auth routes
    Route::post('/auth/logout', [AuthController::class, 'logout']);
    Route::get('/auth/user', [AuthController::class, 'user']);
    Route::put('/auth/profile', [AuthController::class, 'updateProfile']);
    Route::put('/auth/password', [AuthController::class, 'updatePassword']);

    // User Management routes (Admin only)
    Route::middleware(['role:admin'])->group(function () {
        Route::get('/users', [UserController::class, 'index']);
        Route::post('/users', [UserController::class, 'store']);
        Route::get('/users/stats', [UserController::class, 'getStats']);
        Route::get('/users/roles-permissions', [UserController::class, 'getRolesAndPermissions']);
        Route::get('/users/{user}', [UserController::class, 'show']);
        Route::put('/users/{user}', [UserController::class, 'update']);
        Route::delete('/users/{user}', [UserController::class, 'destroy']);
        Route::put('/users/{user}/reset-password', [UserController::class, 'resetPassword']);
        Route::post('/users/{user}/generate-pin', [UserController::class, 'generatePin']);
        Route::delete('/users/{user}/remove-pin', [UserController::class, 'removePin']);
    });

    // Waiters list for filtering (accessible to users who can view orders)
    Route::middleware(['permission:view_orders'])->group(function () {
        Route::get('/waiters', [UserController::class, 'getWaiters']);
    });

    // Waiter Performance routes
    Route::middleware(['permission:view_own_sales'])->group(function () {
        Route::get('/waiter/my-sales', [WaiterController::class, 'getMySales']);
        Route::get('/waiter/my-orders', [WaiterController::class, 'getMyOrders']);
        Route::get('/waiter/my-payments', [WaiterController::class, 'getMyPayments']);
        Route::get('/waiter/daily-summary', [WaiterController::class, 'getDailySummary']);
    });
    
    Route::middleware(['role:admin,manager,waiter'])->group(function () {
        Route::get('/waiter/leaderboard', [WaiterController::class, 'getLeaderboard']);
    });
    
    Route::middleware(['role:admin,manager'])->group(function () {
        Route::get('/waiter/performance', [WaiterController::class, 'getWaitersPerformance']);
    });

    // POS Menu routes (Read-only for ordering - accessible by POS users)
    Route::middleware(['permission:access_pos'])->group(function () {
        Route::get('/pos/menu/categories', [MenuController::class, 'posCategories']);
        Route::get('/pos/menu/items', [MenuController::class, 'posItems']);
    });

    // Menu Management routes (Only Admin/Manager/Inventory Manager can access)
    Route::middleware(['role:admin,manager,inventory_manager'])->group(function () {
        Route::get('/menu/categories', [MenuController::class, 'categories']);
        Route::get('/menu/categories/{category}', [MenuController::class, 'showCategory']);
        Route::get('/menu/items', [MenuController::class, 'items']);
        Route::get('/menu/items/{item}', [MenuController::class, 'show']);
        
        // Management operations require manage_menu permission
        Route::middleware(['permission:manage_menu'])->group(function () {
            Route::post('/menu/categories', [MenuController::class, 'storeCategory']);
            Route::put('/menu/categories/{category}', [MenuController::class, 'updateCategory']);
            Route::delete('/menu/categories/{category}', [MenuController::class, 'destroyCategory']);
            Route::post('/menu/items', [MenuController::class, 'storeItem']);
            Route::put('/menu/items/{item}', [MenuController::class, 'updateItem']);
            Route::post('/menu/items/{item}', [MenuController::class, 'updateItem']); // For method spoofing
            Route::delete('/menu/items/{item}', [MenuController::class, 'destroyItem']);
        });
    });

    // Table routes (POS access required)
    Route::middleware(['permission:access_pos'])->group(function () {
        Route::options('/tables', [TableController::class, 'options']);
        Route::get('/tables', [TableController::class, 'index']);
        Route::post('/tables', [TableController::class, 'store']);
        Route::put('/tables/{table}', [TableController::class, 'update']);
        Route::put('/tables/{table}/status', [TableController::class, 'updateStatus']);
    });

    // Customer routes (POS access required)
    Route::middleware(['permission:access_pos'])->group(function () {
        Route::get('/customers', [CustomerController::class, 'index']);
        Route::post('/customers', [CustomerController::class, 'store']);
        Route::get('/customers/{customer}', [CustomerController::class, 'show']);
        Route::put('/customers/{customer}', [CustomerController::class, 'update']);
        Route::get('/customers/search/{phone}', [CustomerController::class, 'findByPhone']);
    });

    // Order routes (POS access required)
    Route::middleware(['permission:access_pos'])->group(function () {
        Route::get('/orders', [OrderController::class, 'index']);
        Route::post('/orders', [OrderController::class, 'store']);
        Route::get('/orders/{order}', [OrderController::class, 'show']);
        Route::put('/orders/{order}', [OrderController::class, 'update']);
        Route::put('/orders/{order}/status', [OrderController::class, 'updateStatus']);
        Route::put('/orders/{order}/payment-status', [OrderController::class, 'updatePaymentStatus']);
        Route::delete('/orders/{order}', [OrderController::class, 'cancel']);
        Route::post('/orders/{order}/items', [OrderController::class, 'addItem']);
        Route::put('/orders/{order}/items/{item}', [OrderController::class, 'updateItem']);
        Route::delete('/orders/{order}/items/{item}', [OrderController::class, 'removeItem']);
    });

    // Payment routes (Payment processing permission required)
    Route::middleware(['permission:process_payments'])->group(function () {
        Route::get('/orders/{order}/payments', [PaymentController::class, 'index']);
        Route::post('/orders/{order}/payments', [PaymentController::class, 'store']);
        Route::put('/payments/{payment}', [PaymentController::class, 'update']);
        Route::post('/payments/{payment}/refund', [PaymentController::class, 'refund']);
        Route::post('/payments/mpesa/stk-push', [PaymentController::class, 'mpesaStkPush']);
        Route::post('/payments/mpesa/callback', [PaymentController::class, 'mpesaCallback']);
    });

    // Kitchen Display System routes (Kitchen access required)
    Route::middleware(['permission:access_kitchen'])->group(function () {
        Route::get('/kitchen/tickets', [KitchenController::class, 'tickets']);
        Route::put('/kitchen/tickets/{ticket}/complete', [KitchenController::class, 'complete']);
        Route::put('/kitchen/tickets/{ticket}/priority', [KitchenController::class, 'updatePriority']);
        Route::put('/kitchen/tickets/{ticket}/time', [KitchenController::class, 'updateEstimatedTime']);
        Route::get('/kitchen/stats', [KitchenController::class, 'stats']);
    });

    // Inventory routes (Inventory access required)
    Route::middleware(['permission:view_inventory'])->group(function () {
        Route::get('/inventory/alerts/all', [InventoryController::class, 'alerts']);
        Route::get('/inventory/summary/stats', [InventoryController::class, 'summary']);
        Route::get('/inventory', [InventoryController::class, 'index']);
        Route::get('/inventory/{item}', [InventoryController::class, 'show']);
        Route::get('/inventory/{item}/movements', [InventoryController::class, 'stockMovements']);
    });
    
    Route::middleware(['permission:manage_inventory'])->group(function () {
        Route::post('/inventory', [InventoryController::class, 'store']);
        Route::put('/inventory/{item}', [InventoryController::class, 'update']);
        Route::patch('/inventory/{item}/price', [InventoryController::class, 'updatePrice']);
        Route::delete('/inventory/{item}', [InventoryController::class, 'destroy']);
        Route::post('/inventory/{item}/adjust', [InventoryController::class, 'adjustStock']);
    });

    // Kitchen Issuance routes (Inventory access required)
    Route::middleware(['permission:view_inventory'])->group(function () {
        Route::get('/kitchen-issuances', [\App\Http\Controllers\KitchenIssuanceController::class, 'index']);
        Route::get('/kitchen-issuances/summary', [\App\Http\Controllers\KitchenIssuanceController::class, 'summary']);
        Route::get('/kitchen-issuances/top-items', [\App\Http\Controllers\KitchenIssuanceController::class, 'topIssuedItems']);
        Route::get('/kitchen-issuances/{issuance}', [\App\Http\Controllers\KitchenIssuanceController::class, 'show']);
    });
    
    Route::middleware(['permission:manage_inventory'])->group(function () {
        Route::post('/kitchen-issuances', [\App\Http\Controllers\KitchenIssuanceController::class, 'store']);
        Route::post('/kitchen-issuances/{issuance}/receive', [\App\Http\Controllers\KitchenIssuanceController::class, 'receive']);
        Route::post('/kitchen-issuances/{issuance}/cancel', [\App\Http\Controllers\KitchenIssuanceController::class, 'cancel']);
    });

    // Expense routes (Admin/Manager/Cashier/Accountant access required)
    Route::middleware(['role:admin,manager,cashier,accountant'])->group(function () {
        Route::get('/expenses', [ExpenseController::class, 'index']);
        Route::post('/expenses', [ExpenseController::class, 'store']);
        Route::get('/expenses/summary', [ExpenseController::class, 'getSummary']);
        Route::get('/expenses/summary-enhanced', [ExpenseController::class, 'getExpenseSummaryEnhanced']);
        Route::get('/expenses/pay-later', [ExpenseController::class, 'getPayLaterExpenses']);
        Route::get('/expenses/categories', [ExpenseController::class, 'getCategories']);
        Route::post('/expenses/categories', [ExpenseController::class, 'storeCategory']);
        Route::put('/expenses/categories/{category}', [ExpenseController::class, 'updateCategory']);
        Route::get('/expenses/{expense}', [ExpenseController::class, 'show']);
        Route::put('/expenses/{expense}', [ExpenseController::class, 'update']);
        Route::post('/expenses/{expense}/approve', [ExpenseController::class, 'approve']);
        Route::post('/expenses/{expense}/reject', [ExpenseController::class, 'reject']);
        Route::post('/expenses/{expense}/mark-paid', [ExpenseController::class, 'markAsPaid']);
        Route::post('/expenses/{expense}/mark-pay-later-paid', [ExpenseController::class, 'markPayLaterAsPaid']);
        Route::put('/expenses/{expense}/due-date', [ExpenseController::class, 'updateDueDate']);
        Route::get('/expenses/{expense}/attachments/{attachmentIndex}', [ExpenseController::class, 'downloadAttachment']);
    });

    // Petty Cash routes (Admin/Manager/Cashier access required)
    Route::middleware(['role:admin,manager,cashier'])->group(function () {
        Route::get('/petty-cash/balance', [PettyCashController::class, 'getBalance']);
        Route::get('/petty-cash/transactions', [PettyCashController::class, 'getTransactions']);
        Route::get('/petty-cash/summary', [PettyCashController::class, 'getSummary']);
        Route::post('/petty-cash/deposit', [PettyCashController::class, 'deposit']);
        Route::post('/petty-cash/withdraw', [PettyCashController::class, 'withdraw']);
        Route::put('/petty-cash/settings', [PettyCashController::class, 'updateSettings']);
    });

    // Admin-only petty cash routes
    Route::middleware(['role:admin'])->group(function () {
        Route::post('/petty-cash/adjust', [PettyCashController::class, 'adjust']);
    });

    // Admin-only expense routes
    Route::middleware(['role:admin'])->group(function () {
        Route::delete('/expenses/{expense}', [ExpenseController::class, 'destroy']);
        Route::delete('/expenses/categories/{category}', [ExpenseController::class, 'destroyCategory']);
    });

    // Reports routes (Reports access required)
    Route::middleware(['permission:view_reports'])->group(function () {
        Route::get('/reports/sales', [ReportsController::class, 'salesSummary']);
        Route::get('/reports/payment-method-details', [ReportsController::class, 'paymentMethodDetails']);
        Route::get('/reports/top-items', [ReportsController::class, 'topSellingItems']);
        Route::get('/reports/staff', [ReportsController::class, 'staffPerformance']);
        Route::get('/reports/waiters', [ReportsController::class, 'waiterPerformance']);
        Route::get('/reports/waiter-details', [ReportsController::class, 'waiterDetails']);
        Route::get('/reports/customers', [ReportsController::class, 'customerAnalytics']);
        Route::get('/reports/inventory', [ReportsController::class, 'inventoryReport']);
        Route::get('/reports/expenses', [ReportsController::class, 'expenseSummary']);
        Route::get('/reports/expenses/categories', [ReportsController::class, 'expensesByCategory']);
        Route::get('/reports/expenses/trends', [ReportsController::class, 'expenseTrends']);
        Route::post('/reports/export/sales', [ReportsController::class, 'exportSales']);
    });
    
    Route::middleware(['permission:view_financial_reports'])->group(function () {
        Route::get('/reports/financial', [ReportsController::class, 'financialSummary']);
    });

    // Settings routes (All authenticated users can access)
    Route::get('/settings', [SettingsController::class, 'getSettings']);
    Route::get('/settings/printer', [SettingsController::class, 'getPrinterSettings']);
    Route::post('/settings/printer', [SettingsController::class, 'savePrinterSettings']);
    
    // Admin/Manager only settings
    Route::middleware(['role:admin,manager'])->group(function () {
        Route::put('/settings', [SettingsController::class, 'updateSettings']);
    });
});

// Webhook routes (no auth required)
Route::post('/webhooks/mpesa', [PaymentController::class, 'mpesaWebhook']);