<?php

use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\SearchController;
use App\Http\Controllers\Api\UserController;
use App\Http\Controllers\Api\StaffController;
use App\Http\Controllers\Api\SupplierController;
use App\Http\Controllers\Api\CustomerController;
use App\Http\Controllers\Api\BrandController;
use App\Http\Controllers\Api\CategoryController;
use App\Http\Controllers\Api\InventoryController;
use App\Http\Controllers\Api\OrderController;
use App\Http\Controllers\Api\EmployeeController;
use App\Http\Controllers\Api\AttendanceController;
use App\Http\Controllers\Api\PayrollController;
use App\Http\Controllers\Api\ReportController;
use App\Http\Controllers\Api\ContractTemplateController;
use App\Http\Controllers\Api\InstallmentController;
use App\Http\Controllers\Api\TransactionController;
use App\Http\Controllers\Api\TransactionCategoryController;
use App\Http\Controllers\Api\AccountController;
use App\Http\Controllers\Api\AccessoryPurchaseController;
use App\Http\Controllers\Api\AccessoryController;
use App\Http\Controllers\Api\AccessoryStockAdjustmentController;
use App\Http\Controllers\Api\ExpenseCategoryController;
use App\Http\Controllers\Api\ExpenseController;
use App\Http\Controllers\Api\DashboardController;



use App\Http\Controllers\Api\InventoryItemController;



use App\Http\Controllers\Api\PurchaseController;
use App\Http\Controllers\Api\SaleController;
use App\Http\Controllers\Api\SettingController;
use Illuminate\Support\Facades\Route;

// ============================================
// PUBLIC ROUTES
// ============================================
Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

// ============================================
// PROTECTED ROUTES
// ============================================
Route::middleware('auth:sanctum')->group(function () {

    // ============================================
    // AUTH ROUTES
    // ============================================
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/me', [AuthController::class, 'me']);

    // ============================================
    // USER MANAGEMENT
    // ============================================
    Route::apiResource('users', UserController::class);


    Route::prefix('dashboard')->group(function () {
        Route::get('/stats', [DashboardController::class, 'stats']);
        Route::get('/payment-stats', [DashboardController::class, 'paymentStats']);
        Route::get('/revenue-trend', [DashboardController::class, 'revenueTrend']);
        Route::get('/top-products', [DashboardController::class, 'topProducts']);
        Route::get('/recent-activity', [DashboardController::class, 'recentActivity']);
    });




    // Staff Routes
    Route::apiResource('staff', StaffController::class);
    Route::post('/staff/{id}/toggle-status', [StaffController::class, 'toggleStatus']);
    Route::get('/staff-active', [StaffController::class, 'activeStaff']);
    Route::get('/staff-inactive', [StaffController::class, 'inactiveStaff']);

    // ============================================
    // SUPPLIERS
    // ============================================
    Route::apiResource('suppliers', SupplierController::class);
    Route::get('/suppliers-for-product', [SupplierController::class, 'forProduct']);
    Route::post('/suppliers/{id}/toggle-status', [SupplierController::class, 'toggleStatus']);
    Route::get('/suppliers/active', [SupplierController::class, 'activeSuppliers']);
    Route::get('/suppliers/inactive', [SupplierController::class, 'inactiveSuppliers']);
    Route::get('/suppliers/search', [SupplierController::class, 'search']);

    // ============================================
    // CUSTOMERS
    // ============================================
    Route::apiResource('customers', CustomerController::class);
    Route::post('/customers/{id}/toggle-status', [CustomerController::class, 'toggleStatus']);
    Route::get('/customers/{id}/purchase-history', [CustomerController::class, 'purchaseHistory']);
    Route::get('/customers-active', [CustomerController::class, 'activeCustomers']);
    Route::get('/customers-with-due', [CustomerController::class, 'customersWithDue']);
    Route::get('/customers-by-type/{type}', [CustomerController::class, 'getByType']);
    Route::get('/customer/stats', [CustomerController::class, 'getStats']);

    // ============================================
    // BRANDS
    // ============================================
    Route::apiResource('brands', BrandController::class);
    Route::post('/brands/{id}/toggle-status', [BrandController::class, 'toggleStatus']);
    Route::get('/brands-active', [BrandController::class, 'activeBrands']);

    // ============================================
    // CATEGORIES
    // ============================================
    Route::apiResource('categories', CategoryController::class);
    Route::post('/categories/{id}/toggle-status', [CategoryController::class, 'toggleStatus']);
    Route::get('/categories-active', [CategoryController::class, 'activeCategories']);

    // ============================================
    // INVENTORY
    // ============================================
    Route::apiResource('inventory', InventoryController::class);
    Route::get('/inventory-low-stock', [InventoryController::class, 'lowStock']);
    Route::get('/inventory-out-of-stock', [InventoryController::class, 'outOfStock']);
    Route::get('/inventory-available', [InventoryController::class, 'available']);
    Route::post('/inventory/{id}/adjust-stock', [InventoryController::class, 'adjustStock']);



    // Inventory (Products) routes
    Route::prefix('inventory')->group(function () {
        Route::get('/', [InventoryController::class, 'index']);
        Route::post('/', [InventoryController::class, 'store']);
        Route::get('/low-stock', [InventoryController::class, 'lowStock']);
        Route::get('/out-of-stock', [InventoryController::class, 'outOfStock']);
        Route::get('/available', [InventoryController::class, 'available']);
        Route::get('/{id}', [InventoryController::class, 'show']);
        Route::put('/{id}', [InventoryController::class, 'update']);
        Route::delete('/{id}', [InventoryController::class, 'destroy']);
        Route::post('/{id}/adjust-stock', [InventoryController::class, 'adjustStock']);
    });

    // Inventory Items (Individual Devices) routes
    Route::prefix('inventory-items')->group(function () {
        Route::get('/', [InventoryItemController::class, 'index']);
        Route::post('/', [InventoryItemController::class, 'store']);
        Route::post('/bulk', [InventoryItemController::class, 'bulkStore']);
        Route::post('/search-imei', [InventoryItemController::class, 'searchByImei']);
        Route::get('/{id}', [InventoryItemController::class, 'show']);
        Route::put('/{id}', [InventoryItemController::class, 'update']);
        Route::delete('/{id}', [InventoryItemController::class, 'destroy']);
        Route::post('/{id}/mark-sold', [InventoryItemController::class, 'markAsSold']);
    });

    // Get items for specific inventory product
    Route::get('/inventory/{inventoryId}/items', [InventoryItemController::class, 'index']);
    Route::get('/inventory/{inventoryId}/items/available', [InventoryItemController::class, 'available']);
    Route::get('/inventory/{inventoryId}/items/sold', [InventoryItemController::class, 'sold']);


    Route::get('/search', [SearchController::class, 'index']);

    // ============================================
    // ORDERS
    // ============================================


    Route::prefix('orders')->group(function () {
        Route::get('/', [OrderController::class, 'index']);
        Route::post('/', [OrderController::class, 'store']);        // create order + reserve items
        Route::get('{order}', [OrderController::class, 'show']);
        Route::put('{order}', [OrderController::class, 'update']);  // update header only (notes, dates, customer)
        Route::delete('{order}', [OrderController::class, 'destroy']);

        Route::post('{order}/confirm', [OrderController::class, 'confirm']);
        Route::post('{order}/complete', [OrderController::class, 'complete']); // mark items sold
        Route::post('{order}/cancel', [OrderController::class, 'cancel']);     // release reserved items

        Route::post('{order}/payments', [OrderController::class, 'addPayment']);
    });




    // ============================================
    // PURCHASES
    // ============================================
    Route::apiResource('purchases', PurchaseController::class)->except(['destroy']);
    Route::post('/purchases/{id}/cancel', [PurchaseController::class, 'cancel']);
    Route::post('/purchases/{id}/payments', [PurchaseController::class, 'addPayment']);
    Route::get('/purchases/{id}/payments', [PurchaseController::class, 'getPayments']);
    Route::get('/purchases-pending-payments', [PurchaseController::class, 'pendingPayments']);
    Route::get('/purchases-statistics', [PurchaseController::class, 'statistics']);

    // ============================================
    // SALES
    // ============================================
    Route::apiResource('sales', SaleController::class)->except(['destroy', 'update']);
    Route::post('/sales/{id}/cancel', [SaleController::class, 'cancel']);
    Route::post('/sales/{id}/payments', [SaleController::class, 'addPayment']);
    Route::get('/sales/{id}/payments', [SaleController::class, 'getPayments']);
    Route::get('/sales/{id}/installments', [SaleController::class, 'getInstallments']);
    Route::post('/installments/{id}/pay', [SaleController::class, 'payInstallment']);
    Route::get('/sales-pending-payments', [SaleController::class, 'pendingPayments']);
    Route::get('/installments-overdue', [SaleController::class, 'overdueInstallments']);
    Route::get('/installments-today-due', [SaleController::class, 'todayDueInstallments']);
    Route::get('/sales-statistics', [SaleController::class, 'statistics']);
    Route::get('/sales-top-products', [SaleController::class, 'topSellingProducts']);
    Route::get('/sales-by-staff', [SaleController::class, 'salesByStaff']);
    Route::get('/sales-daily-report', [SaleController::class, 'dailySalesReport']);

    // ============================================
    // SETTINGS
    // ============================================
    Route::get('/settings', [SettingController::class, 'index']);
    Route::get('/settings/group/{group}', [SettingController::class, 'getByGroup']);
    Route::get('/settings/{key}', [SettingController::class, 'show']);
    Route::post('/settings', [SettingController::class, 'update']);
    Route::post('/settings/bulk', [SettingController::class, 'bulkUpdate']);
    Route::delete('/settings/{key}', [SettingController::class, 'destroy']);


    // =========================================================
    // EMP ROUTES
    // =========================================================

    // Employees
    Route::apiResource('employees', EmployeeController::class);

    // Attendance
    // Route::post('attendance/clock-in', [AttendanceController::class, 'clockIn']);
    // Route::post('attendance/clock-out', [AttendanceController::class, 'clockOut']);
    // Route::get('attendance/history', [AttendanceController::class, 'history']);

    // Attendance CRUD operations
    Route::prefix('attendance')->group(function () {
        // Existing routes
        Route::post('clock-in', [AttendanceController::class, 'clockIn']);
        Route::post('clock-out', [AttendanceController::class, 'clockOut']);
        Route::get('history', [AttendanceController::class, 'history']);

        // NEW ROUTES - Add these
        Route::get('{id}', [AttendanceController::class, 'show']);
        Route::post('manual', [AttendanceController::class, 'manualEntry']);
        Route::put('{id}', [AttendanceController::class, 'update']);
        Route::delete('{id}', [AttendanceController::class, 'destroy']);
    });

    // Payroll
    // Route::get('payrolls', [PayrollController::class, 'index']);
    // Route::get('payrolls/{payroll}', [PayrollController::class, 'show']);
    // Route::post('payrolls/generate', [PayrollController::class, 'generate']);
    // Route::patch('payrolls/{payroll}/status', [PayrollController::class, 'updateStatus']);

    // List all payrolls
    Route::get('payroll', [PayrollController::class, 'index']);

    // Show single payroll
    Route::get('payroll/{id}', [PayrollController::class, 'show']);

    // Generate new payroll
    Route::post('payroll/generate', [PayrollController::class, 'generate']);

    // Update payroll (draft only)
    Route::put('payroll/{id}', [PayrollController::class, 'update']);

    // Update payroll status
    Route::patch('payroll/{id}/status', [PayrollController::class, 'updateStatus']);

    // Delete payroll (draft only)
    Route::delete('payroll/{id}', [PayrollController::class, 'destroy']);



    // Report Routes
    Route::prefix('reports')->group(function () {
        // Summary and generation
        Route::get('/summary', [ReportController::class, 'getSummary']);
        Route::get('/generate', [ReportController::class, 'generateReport']);

        // Export
        Route::get('/export', [ReportController::class, 'exportReport']);
        Route::get('/export-all', [ReportController::class, 'exportAll']);

        // Email
        Route::post('/email', [ReportController::class, 'emailReport']);
        Route::post('/email-all', [ReportController::class, 'emailAllReports']);

        // Scheduled Reports
        Route::get('/scheduled', [ReportController::class, 'getScheduledReports']);
        Route::post('/schedule', [ReportController::class, 'createSchedule']);
        Route::put('/schedule/{id}', [ReportController::class, 'updateSchedule']);
        Route::delete('/schedule/{id}', [ReportController::class, 'deleteSchedule']);
    });



    // ============================================
    // INSTALLMENTS
    // ============================================
    Route::prefix('installments')->group(function () {
        // List and CRUD
        Route::get('/', [InstallmentController::class, 'index']);
        Route::post('/', [InstallmentController::class, 'store']);
        Route::get('/{installment}', [InstallmentController::class, 'show']);
        Route::patch('/{installment}/status', [InstallmentController::class, 'updateStatus']);

        // Payment Schedule
        Route::get('/{installment}/schedule', [InstallmentController::class, 'getPaymentSchedule']);
        Route::post('/payments/{payment}/record', [InstallmentController::class, 'recordPayment']);

        // Contract Management
        Route::post('/{installment}/generate-contract', [InstallmentController::class, 'generateContract']);
        Route::get('/{installment}/download-contract', [InstallmentController::class, 'downloadContract']);

        // Document Management
        Route::post('/{installment}/documents', [InstallmentController::class, 'uploadDocument']);
        Route::delete('/documents/{document}', [InstallmentController::class, 'deleteDocument']);

        // Reports and Statistics
        Route::get('/reports/overdue', [InstallmentController::class, 'overdueInstallments']);
        Route::get('/reports/upcoming', [InstallmentController::class, 'upcomingPayments']);
        Route::get('/reports/statistics', [InstallmentController::class, 'statistics']);
    });

    // Contract Templates (for admin)
    Route::prefix('contract-templates')->group(function () {
        Route::get('/', [ContractTemplateController::class, 'index']);
        Route::post('/', [ContractTemplateController::class, 'store']);
        Route::get('/{template}', [ContractTemplateController::class, 'show']);
        Route::put('/{template}', [ContractTemplateController::class, 'update']);
        Route::delete('/{template}', [ContractTemplateController::class, 'destroy']);
        Route::patch('/{template}/set-default', [ContractTemplateController::class, 'setAsDefault']);
    });



    /*
|--------------------------------------------------------------------------
| Transaction & Accounting Routes
|--------------------------------------------------------------------------
*/

    // Transactions
    Route::prefix('transactions')->group(function () {
        Route::get('/', [TransactionController::class, 'index']);
        Route::get('/stats', [TransactionController::class, 'stats']);
        Route::get('/cash-flow', [TransactionController::class, 'cashFlow']);
        Route::get('/{id}', [TransactionController::class, 'show']);

        // Record transactions
        Route::post('/expense', [TransactionController::class, 'recordExpense']);
        Route::post('/income', [TransactionController::class, 'recordIncome']);
        Route::post('/transfer', [TransactionController::class, 'transfer']);

        // Cancel transaction
        Route::post('/{id}/cancel', [TransactionController::class, 'cancel']);
    });

    // Accounts
    Route::prefix('accounts')->group(function () {
        Route::get('/', [AccountController::class, 'index']);
        Route::get('/{id}', [AccountController::class, 'show']);
        Route::post('/', [AccountController::class, 'store']);
        Route::put('/{id}', [AccountController::class, 'update']);
        Route::delete('/{id}', [AccountController::class, 'destroy']);

        // Account transactions
        Route::get('/{id}/transactions', [AccountController::class, 'transactions']);
        Route::get('/{id}/balance', [AccountController::class, 'balance']);
    });

    // Transaction Categories
    Route::apiResource('transaction-categories', TransactionCategoryController::class);

    /*
|--------------------------------------------------------------------------
| Updated Purchase Routes (example)
|--------------------------------------------------------------------------
*/

    Route::prefix('purchases')->group(function () {
        // ... existing purchase routes ...

        // Payment using new transaction system
        Route::post('/{id}/payments', [PurchaseController::class, 'addPayment']);
        Route::get('/{id}/transactions', [PurchaseController::class, 'getTransactions']);
    });


    // Accessories Routes
    Route::prefix('accessories')->group(function () {
        Route::get('/', [AccessoryController::class, 'index']);
        Route::post('/', [AccessoryController::class, 'store']);
        Route::get('/low-stock', [AccessoryController::class, 'lowStock']);
        Route::get('/categories', [AccessoryController::class, 'categories']);
        Route::get('/{id}', [AccessoryController::class, 'show']);
        Route::put('/{id}', [AccessoryController::class, 'update']);
        Route::delete('/{id}', [AccessoryController::class, 'destroy']);
    });

    // Accessory Purchases Routes
    Route::prefix('accessory-purchases')->group(function () {
        Route::get('/', [AccessoryPurchaseController::class, 'index']);
        Route::post('/', [AccessoryPurchaseController::class, 'store']);
        Route::get('/{id}', [AccessoryPurchaseController::class, 'show']);
        Route::delete('/{id}', [AccessoryPurchaseController::class, 'destroy']);
    });
    Route::post('accessory-stock-adjustments', [AccessoryStockAdjustmentController::class, 'store']);



    // Expense Categories
    Route::prefix('expense-categories')->group(function () {
        Route::get('/', [ExpenseCategoryController::class, 'index']);
        Route::get('/active', [ExpenseCategoryController::class, 'activeCategories']); // for dropdowns
        Route::post('/', [ExpenseCategoryController::class, 'store']);
        Route::get('/{id}', [ExpenseCategoryController::class, 'show']);
        Route::put('/{id}', [ExpenseCategoryController::class, 'update']);
        Route::delete('/{id}', [ExpenseCategoryController::class, 'destroy']);
    });

    // Expenses
    Route::prefix('expenses')->group(function () {
        Route::get('/', [ExpenseController::class, 'index']);
        Route::post('/', [ExpenseController::class, 'store']);
        Route::get('/{id}', [ExpenseController::class, 'show']);
        Route::put('/{id}', [ExpenseController::class, 'update']);
        Route::delete('/{id}', [ExpenseController::class, 'destroy']);
        Route::post('/{id}/upload-receipt', [ExpenseController::class, 'uploadReceipt']);
        Route::delete('/{id}/delete-receipt', [ExpenseController::class, 'deleteReceipt']);
    });

    Route::get('/accessoriess/available', [AccessoryController::class, 'availableForSale']);
});
