<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

// Admin Routes
Route::prefix('admin')->group(function () {
    Route::get('/login', 'App\Http\Controllers\AdminWebController@showLoginForm')->name('admin.login');
    Route::post('/login', 'App\Http\Controllers\AdminWebController@login')->name('admin.login.post');
    Route::post('/logout', 'App\Http\Controllers\AdminWebController@logout')->name('admin.logout');

    Route::middleware(['auth:admin'])->group(function () {
        Route::get('/dashboard', 'App\Http\Controllers\AdminWebController@dashboard')->name('admin.dashboard');
        
        // Users Management
        Route::get('/users', 'App\Http\Controllers\AdminWebController@usersIndex')->name('admin.users.index');
        
        // Drivers Management
        Route::get('/drivers', 'App\Http\Controllers\AdminWebController@driversIndex')->name('admin.drivers.index');
        Route::post('/drivers/{driver}/approve', 'App\Http\Controllers\AdminWebController@approveDriver')->name('admin.drivers.approve');

        // Transport Management
        Route::get('/transport', 'App\Http\Controllers\TransportController@index')->name('admin.transport.index');
        Route::post('/transport/company', 'App\Http\Controllers\TransportController@storeCompany')->name('admin.transport.company.store');
        Route::post('/transport/company/{company}/route', 'App\Http\Controllers\TransportController@storeRoute')->name('admin.transport.route.store');

        // Financials & Settings
        Route::get('/transactions', 'App\Http\Controllers\TransactionController@index')->name('admin.transactions.index');
        Route::get('/settings', 'App\Http\Controllers\TransactionController@settings')->name('admin.settings');
        Route::post('/settings', 'App\Http\Controllers\TransactionController@updateSettings')->name('admin.settings.update');
    });
});

// Secure System Migration URL (for cPanel without terminal)
Route::get('/system/migrate', function () {
    $key = request('key');
    if ($key !== env('MIGRATE_KEY')) {
        return response('Unauthorized Access', 403);
    }
    
    $fresh = request('fresh');
    
    try {
        if ($fresh === 'true') {
            \Illuminate\Support\Facades\Artisan::call('migrate:fresh', ['--force' => true]);
            return "Fresh Migration Successful: " . \Illuminate\Support\Facades\Artisan::output();
        } else {
            \Illuminate\Support\Facades\Artisan::call('migrate', ['--force' => true]);
            return "Migration Successful: " . \Illuminate\Support\Facades\Artisan::output();
        }
    } catch (\Exception $e) {
        return "Migration Failed: " . $e->getMessage();
    }
});
