<?php

use App\Http\Controllers\Admin\CarController as AdminCarController;
use App\Http\Controllers\Admin\DashboardController as AdminDashboardController;
use App\Http\Controllers\Admin\InquiryController as AdminInquiryController;
use App\Http\Controllers\Admin\SettingsController as AdminSettingsController;
use App\Http\Controllers\Admin\BranchController;
use App\Http\Controllers\Admin\AnalyticsController;
use App\Http\Controllers\CarController;
use App\Http\Controllers\InquiryController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\Customer\AuthController as CustomerAuthController;
use App\Http\Controllers\Customer\DashboardController as CustomerDashboardController;

// Frontend Routes
Route::get('/', function () {
    $latest_cars = (new \App\Services\CarService)->getLatestCars(6);
    $settings = \App\Models\Setting::first();

    return view('home', compact('latest_cars', 'settings'));
})->name('home');

// Customer Auth Routes
Route::prefix('account')->name('customer.')->group(function () {
    Route::middleware('guest:customer')->group(function () {
        Route::get('/login', [CustomerAuthController::class, 'showLogin'])->name('login');
        Route::post('/login', [CustomerAuthController::class, 'login'])->name('login.post')->middleware('throttle:5,1');
        Route::get('/register', [CustomerAuthController::class, 'showRegister'])->name('register');
        Route::post('/register', [CustomerAuthController::class, 'register'])->name('register.post')->middleware('throttle:3,1');
    });

    Route::middleware('auth:customer')->group(function () {
        Route::get('/dashboard', [CustomerDashboardController::class, 'index'])->name('dashboard');
        Route::get('/rentals', [CustomerDashboardController::class, 'rentals'])->name('rentals');
        Route::get('/rentals/{id}', [CustomerDashboardController::class, 'rentalShow'])->name('rental.show');
        Route::get('/inquiries', [CustomerDashboardController::class, 'inquiries'])->name('inquiries');
        Route::get('/profile', [CustomerDashboardController::class, 'profile'])->name('profile');
        Route::put('/profile', [CustomerDashboardController::class, 'updateProfile'])->name('profile.update');
        Route::post('/logout', [CustomerAuthController::class, 'logout'])->name('logout');
    });
});

Route::get('/cars', [CarController::class, 'index'])->name('cars.index');
Route::get('/cars/{id}', [CarController::class, 'show'])->name('cars.show');
Route::post('/inquiries', [InquiryController::class, 'store'])->name('inquiries.store')->middleware('throttle:5,1');
Route::get('lang/{lang}', [App\Http\Controllers\LanguageController::class, 'switch'])->name('lang.switch');

// Chat Routes
Route::get('/chat/messages', [App\Http\Controllers\ChatController::class, 'getMessages'])->name('chat.messages');
Route::post('/chat/send', [App\Http\Controllers\ChatController::class, 'sendMessage'])->name('chat.send');

// Admin Routes
Route::middleware(['auth', 'verified'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('dashboard');
    
    // Chat Management
    Route::get('chat', [App\Http\Controllers\Admin\ChatController::class, 'index'])->name('chat.index');
    Route::get('chat/{id}', [App\Http\Controllers\Admin\ChatController::class, 'show'])->name('chat.show');
    Route::post('chat/{id}/reply', [App\Http\Controllers\Admin\ChatController::class, 'reply'])->name('chat.reply');
    
    // Analytics Module
    Route::middleware('permission:view_analytics')->group(function () {
        Route::get('/analytics', [AnalyticsController::class, 'dashboard'])->name('analytics.dashboard');
        Route::get('/analytics/report', [AnalyticsController::class, 'report'])->name('analytics.report');
        Route::get('/analytics/vehicles', [AnalyticsController::class, 'vehicles'])->name('analytics.vehicles');
        Route::get('/analytics/depreciation', [AnalyticsController::class, 'depreciation'])->name('analytics.depreciation');
        Route::get('/analytics/vehicle-statement', [App\Http\Controllers\Admin\VehicleStatementController::class, 'index'])->name('analytics.vehicle-statement');
        Route::get('/analytics/vehicle-statement/report', [App\Http\Controllers\Admin\VehicleStatementController::class, 'report'])->name('analytics.vehicle-statement.report');
    });

    // Branch Management (Admin Only)
    Route::middleware('permission:view_branches')->group(function () {
        Route::get('branches/{branch}/stats', [BranchController::class, 'stats'])->name('branches.stats');
        Route::resource('branches', BranchController::class);
    });

    // Rental Module
    Route::middleware('permission:view_contracts')->group(function () {
        Route::get('rentals/dashboard', [App\Http\Controllers\Admin\Rental\RentalController::class, 'dashboard'])->name('rentals.dashboard');
        Route::get('rentals/calendar', [App\Http\Controllers\Admin\Rental\RentalController::class, 'calendar'])->name('rentals.calendar');
        Route::get('rentals/{rental}/pdf', [App\Http\Controllers\Admin\Rental\RentalController::class, 'generatePdf'])->name('rentals.pdf');
        
        Route::middleware('permission:create_contracts')->group(function () {
            Route::get('rentals/create', [App\Http\Controllers\Admin\Rental\RentalController::class, 'create'])->name('rentals.create');
            Route::post('rentals', [App\Http\Controllers\Admin\Rental\RentalController::class, 'store'])->name('rentals.store');
        });

        Route::middleware('permission:edit_contracts')->group(function () {
            Route::get('rentals/{rental}/edit', [App\Http\Controllers\Admin\Rental\RentalController::class, 'edit'])->name('rentals.edit');
            Route::put('rentals/{rental}', [App\Http\Controllers\Admin\Rental\RentalController::class, 'update'])->name('rentals.update');
        });

        Route::middleware('permission:close_contracts')->group(function () {
            Route::get('rentals/{rental}/close', [App\Http\Controllers\Admin\Rental\RentalController::class, 'closeScreen'])->name('rentals.close-screen');
            Route::post('rentals/{rental}/close', [App\Http\Controllers\Admin\Rental\RentalController::class, 'close'])->name('rentals.close');
        });

        Route::get('rentals/{rental}', [App\Http\Controllers\Admin\Rental\RentalController::class, 'show'])->name('rentals.show');
        Route::get('rentals', [App\Http\Controllers\Admin\Rental\RentalController::class, 'index'])->name('rentals.index');
    });

    Route::middleware('permission:view_maintenance')->resource('maintenance', App\Http\Controllers\Admin\Rental\MaintenanceController::class);
    
    Route::middleware('permission:view_customers')->group(function () {
        Route::get('violations', [App\Http\Controllers\Admin\Rental\ViolationController::class, 'index'])->name('violations.index');
        Route::patch('violations/{violation}/status', [App\Http\Controllers\Admin\Rental\ViolationController::class, 'updateStatus'])->name('violations.status');
    });

    // Receipts
    Route::middleware('permission:view_receipts')->group(function () {
        Route::get('receipts/{receipt}/pdf', [App\Http\Controllers\Admin\Rental\ReceiptController::class, 'generatePdf'])->name('receipts.pdf');
        Route::post('receipts/{receipt}/cancel', [App\Http\Controllers\Admin\Rental\ReceiptController::class, 'cancel'])->name('receipts.cancel');
        Route::resource('receipts', App\Http\Controllers\Admin\Rental\ReceiptController::class);
    });

    // Expenses & Vouchers
    Route::middleware('permission:view_expenses')->group(function () {
        Route::resource('expenses', App\Http\Controllers\Admin\Rental\ExpenseController::class);
        Route::post('expenses/{expense}/cancel', [App\Http\Controllers\Admin\Rental\ExpenseController::class, 'cancel'])->name('expenses.cancel');
        Route::resource('expense-categories', App\Http\Controllers\Admin\Rental\ExpenseCategoryController::class);
    });
    
    // Vouchers
    Route::middleware('permission:view_vouchers')->group(function () {
        Route::get('vouchers/{voucher}/pdf', [App\Http\Controllers\Admin\Rental\PaymentVoucherController::class, 'generatePdf'])->name('vouchers.pdf');
        Route::resource('vouchers', App\Http\Controllers\Admin\Rental\PaymentVoucherController::class);
    });

    // Invoices
    Route::middleware('permission:view_invoices')->group(function () {
        Route::post('invoices/{invoice}/record-payment', [App\Http\Controllers\Admin\Rental\InvoiceController::class, 'recordPayment'])->name('invoices.recordPayment');
        Route::get('invoices/{invoice}/print', [App\Http\Controllers\Admin\Rental\InvoiceController::class, 'print'])->name('invoices.print');
        Route::get('invoices/{invoice}/print-voucher/{voucherId}', [App\Http\Controllers\Admin\Rental\InvoiceController::class, 'printVoucher'])->name('invoices.printVoucher');
        Route::get('invoices/statistics', [App\Http\Controllers\Admin\Rental\InvoiceController::class, 'statistics'])->name('invoices.statistics');
        Route::resource('invoices', App\Http\Controllers\Admin\Rental\InvoiceController::class);
    });

    // Insurance Module
    Route::middleware('permission:view_insurance')->group(function () {
        Route::resource('insurance-companies', App\Http\Controllers\Admin\Rental\InsuranceCompanyController::class);
        Route::resource('vehicle-insurances', App\Http\Controllers\Admin\Rental\VehicleInsuranceController::class);
        Route::resource('insurance-claims', App\Http\Controllers\Admin\Rental\InsuranceClaimController::class);
        Route::get('vehicle-documents/car/{car_id}', [App\Http\Controllers\Admin\VehicleDocumentController::class, 'getCarDocument'])->name('vehicle-documents.car');
        Route::resource('vehicle-documents', App\Http\Controllers\Admin\VehicleDocumentController::class);
    });

    Route::middleware('permission:view_vehicles')->group(function () {
        Route::middleware('permission:create_vehicles')->group(function () {
            Route::get('cars/create', [AdminCarController::class, 'create'])->name('cars.create');
            Route::post('cars', [AdminCarController::class, 'store'])->name('cars.store');
        });

        Route::middleware('permission:edit_vehicles')->group(function () {
            Route::get('cars/{car}/edit', [AdminCarController::class, 'edit'])->name('cars.edit');
            Route::put('cars/{car}', [AdminCarController::class, 'update'])->name('cars.update');
        });

        Route::middleware('permission:delete_vehicles')->delete('cars/{car}', [AdminCarController::class, 'destroy'])->name('cars.destroy');

        Route::get('cars/{car}', [AdminCarController::class, 'show'])->name('cars.show');
        Route::get('cars', [AdminCarController::class, 'index'])->name('cars.index');
    });

    // HR & Payroll Module
    Route::middleware('permission:view_employees')->resource('employees', App\Http\Controllers\Admin\EmployeeController::class);
    Route::middleware('permission:manage_job_titles')->resource('job-titles', App\Http\Controllers\Admin\JobTitleController::class);
    
    Route::middleware('permission:view_payrolls')->group(function () {
        Route::get('payrolls', [App\Http\Controllers\Admin\PayrollController::class, 'index'])->name('payrolls.index');
        Route::get('payrolls/create', [App\Http\Controllers\Admin\PayrollController::class, 'create'])->name('payrolls.create');
        Route::post('payrolls', [App\Http\Controllers\Admin\PayrollController::class, 'store'])->name('payrolls.store');
        Route::get('payrolls/{cycle}', [App\Http\Controllers\Admin\PayrollController::class, 'show'])->name('payrolls.show');
        Route::get('payrolls/{cycle}/pdf', [App\Http\Controllers\Admin\PayrollController::class, 'exportPdf'])->name('payrolls.pdf');
        Route::get('payrolls/{cycle}/excel', [App\Http\Controllers\Admin\PayrollController::class, 'exportExcel'])->name('payrolls.excel');
        Route::post('payrolls/cycle/{cycle}/approve', [App\Http\Controllers\Admin\PayrollController::class, 'approve'])->name('payrolls.approve');
        Route::patch('payrolls/{payroll}/update', [App\Http\Controllers\Admin\PayrollController::class, 'updatePayroll'])->name('payrolls.update-entry');
        Route::post('payrolls/{payroll}/items', [App\Http\Controllers\Admin\PayrollController::class, 'addItem'])->name('payrolls.add-item');
        Route::delete('payrolls/items/{item}', [App\Http\Controllers\Admin\PayrollController::class, 'deleteItem'])->name('payrolls.delete-item');
    });

    Route::middleware('permission:view_inquiries')->group(function () {
        Route::get('inquiries', [AdminInquiryController::class, 'index'])->name('inquiries.index');
        Route::get('inquiries/{id}', [AdminInquiryController::class, 'show'])->name('inquiries.show');
        Route::patch('inquiries/{id}', [AdminInquiryController::class, 'update'])->name('inquiries.update');
    });

    // Customers Management
    Route::middleware('permission:view_customers')->group(function () {
        Route::get('customers', [App\Http\Controllers\Admin\Customers\CustomerController::class, 'index'])->name('customers.index');
        Route::post('customers', [App\Http\Controllers\Admin\Customers\CustomerController::class, 'store'])->name('customers.store');
        Route::get('customers/{customer}', [App\Http\Controllers\Admin\Customers\CustomerController::class, 'show'])->name('customers.show');
        Route::get('customers/{customer}/export', [App\Http\Controllers\Admin\Customers\CustomerController::class, 'exportProfile'])->name('customers.export');
    });

    // API for Dropdowns
    Route::get('/api/models', [App\Http\Controllers\Admin\BrandModelController::class, 'getModels'])->name('api.models');
    Route::get('/api/trims', [App\Http\Controllers\Admin\BrandModelController::class, 'getTrims'])->name('api.trims');
    Route::get('/api/car-addons/{id}', [App\Http\Controllers\CarController::class, 'fetchAddOns'])->name('api.car-addons');
    Route::get('/api/cars-by-branch/{branch_id?}', [App\Http\Controllers\Admin\Rental\RentalController::class, 'getCarsByBranch'])->name('api.cars-by-branch');

    // Data Management
    Route::middleware('permission:manage_brands')->resource('brands', App\Http\Controllers\Admin\BrandController::class);
    Route::middleware('permission:manage_models')->resource('models', App\Http\Controllers\Admin\CarModelController::class);
    Route::middleware('permission:manage_trims')->resource('trims', App\Http\Controllers\Admin\TrimController::class);

    // Users & Roles Management
    Route::middleware('permission:view_users')->group(function () {
        Route::resource('users', App\Http\Controllers\Admin\UserController::class);
        Route::put('users/{user}/password', [App\Http\Controllers\Admin\UserController::class, 'updatePassword'])->name('users.password.update');
    });
    
    Route::middleware('permission:manage_roles')->resource('roles', App\Http\Controllers\Admin\RoleController::class);
    Route::middleware('permission:view_activity_logs')->get('activity-logs', [App\Http\Controllers\Admin\ActivityLogController::class, 'index'])->name('activity-logs.index');

    // Settings
    Route::middleware('permission:manage_settings')->group(function () {
        Route::get('settings', [AdminSettingsController::class, 'edit'])->name('settings.edit');
        Route::put('settings', [AdminSettingsController::class, 'update'])->name('settings.update');
    });
});

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});

require __DIR__.'/auth.php';
