<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Web\Auth\AuthController;
use App\Http\Controllers\Web\Auth\EmployeeAuthController;
use App\Http\Controllers\Web\Auth\AdminAuthController;
use App\Http\Controllers\Web\Customer\CartController;
use App\Http\Controllers\Web\Customer\MenuController;
use App\Http\Controllers\Web\Customer\OrderController;
use App\Http\Controllers\Web\Customer\PaymentController;
use App\Http\Controllers\Web\Customer\ReviewController;
use App\Http\Controllers\Web\Customer\CareerController;
use App\Http\Controllers\Web\Employee\OrderManagementController;
use App\Http\Controllers\Web\Employee\PaymentConfirmationController;
use App\Http\Controllers\Web\Employee\ReceiptController;
use App\Http\Controllers\Web\Admin\DashboardController;
use App\Http\Controllers\Web\Admin\MenuManagementController;
use App\Http\Controllers\Web\Admin\PromoManagementController;
use App\Http\Controllers\Web\Admin\PaymentMethodController;
use App\Http\Controllers\Web\Admin\CareerManagementController;
use App\Http\Controllers\Web\Admin\SystemSettingController;
use App\Http\Controllers\Web\Admin\ReportController;


// ====================
// PUBLIC PAGES
// ====================

Route::get('/', fn() => view('home'))->name('home');
Route::get('/menu', [MenuController::class, 'index'])->name('menu.public');
Route::get('/careers', [\App\Http\Controllers\Web\Customer\CareerController::class, 'publicIndex'])->name('careers.public');
// ====================
// AUTH PAGES
// ====================

Route::middleware('guest')->group(function () {
    // Customer Auth
    Route::get('/login', [\App\Http\Controllers\Web\Auth\AuthController::class, 'showLoginForm'])->name('login');
    Route::post('/login', [\App\Http\Controllers\Web\Auth\AuthController::class, 'login']);

    Route::get('/register', [\App\Http\Controllers\Web\Auth\AuthController::class, 'showRegistrationForm'])->name('register');
    Route::post('/register', [\App\Http\Controllers\Web\Auth\AuthController::class, 'register']);

    // Employee Auth
    Route::get('/employee/login', [\App\Http\Controllers\Web\Auth\EmployeeAuthController::class, 'showLoginForm'])
        ->name('employee.login.form');
    Route::post('/employee/login', [\App\Http\Controllers\Web\Auth\EmployeeAuthController::class, 'login'])
        ->name('employee.login');

    // Admin Login
    Route::get('/admin/login', [\App\Http\Controllers\Web\Auth\AdminAuthController::class, 'showLoginForm'])
        ->name('admin.login.form');
    Route::post('/admin/login', [\App\Http\Controllers\Web\Auth\AdminAuthController::class, 'login'])
        ->name('admin.login');
});

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// ====================
// CUSTOMER PAGES
// ====================

Route::middleware(['auth.web', 'role.web:customer'])
    ->prefix('customer')
    ->name('customer.')
    ->group(function () {

        Route::get('/dashboard', function () {
            return view('customer.dashboard');
        })->name('dashboard');

        Route::get('/menu', [App\Http\Controllers\Web\Customer\MenuController::class, 'index'])->name('menu.index');

        // Cart Routes
        Route::controller(\App\Http\Controllers\Web\Customer\CartController::class)
            ->prefix('cart')
            ->name('cart.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::post('/', 'store')->name('store');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
                Route::delete('/', 'clear')->name('clear');
            });


        // Orders Routes
        Route::controller(\App\Http\Controllers\Web\Customer\OrderController::class)
            ->prefix('orders')
            ->name('orders.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::post('/{id}/cancel', 'cancel')->name('cancel'); // Changed from put to post
                Route::get('/{id}/rate', 'rate')->name('rate'); 
                Route::post('/{id}/rate', 'submitRating')->name('rate.submit'); 
                Route::get('/{id}/track', 'track')->name('track'); // Add track route
                Route::post('/{id}/request-review', 'requestReview')->name('request-review'); // Optional
            });

        // Payments Routes
        Route::controller(\App\Http\Controllers\Web\Customer\PaymentController::class)
            ->prefix('payments')
            ->name('payments.')
            ->group(function () {
                Route::get('/{orderId}', 'show')->name('show');
                Route::get('/{orderId}/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{paymentId}/upload', 'showUploadForm')->name('upload.form');
                Route::post('/upload', 'upload')->name('upload');
            });

        // Reviews Routes
        Route::controller(\App\Http\Controllers\Web\Customer\ReviewController::class)
            ->prefix('reviews')
            ->name('reviews.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                route::get('/create/{orderItemId}', 'create')->name('create.from-order');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/edit', 'edit')->name('edit');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
            });

        // Careers Routes (Customer)
        Route::controller(\App\Http\Controllers\Web\Customer\CareerController::class)
            ->prefix('careers')
            ->name('careers.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/apply', 'apply')->name('apply');
                Route::post('/{id}/apply', 'submitApplication')->name('apply.submit');
                Route::get('/applications', 'myApplications')->name('applications.index');
                Route::get('/applications/{id}', 'showApplication')->name('applications.show');
                Route::put('/applications/{id}/cancel', 'cancelApplication')->name('applications.cancel');
            });

        Route::get('/profile', [AuthController::class, 'profile'])
            ->name('profile.index');
        Route::get('/profile/edit', [AuthController::class, 'editProfile'])
            ->name('profile.edit');
        Route::put('/profile', [AuthController::class, 'updateProfile'])
            ->name('profile.update');

        // Cart count update
        Route::post('/cart/update-count', function (Request $request) {
            Session::put('cart_count', $request->count);
            return response()->json(['success' => true]);
        })->name('cart.update-count');
    });

    Route::middleware(['auth'])
    ->get('/customer/rating-history', function(Request $request) {
        // Check authentication
        if (!auth()->check()) {
            return redirect()->route('login');
        }
        
        $user = auth()->user();
        
        // Only for customers
        if ($user->role !== 'customer') {
            return redirect()->route($user->role . '.dashboard')
                ->with('error', 'Access denied');
        }
        
        $perPage = $request->get('limit', 10);
        
        // Get reviews
        $reviews = \App\Models\Review::where('customer_id', $user->id)
            ->with(['order', 'menu'])
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
        
        // Calculate stats
        $stats = [
            'total' => $reviews->total(),
            'average' => round($reviews->avg('rating') ?? 0, 1),
            'recent' => \App\Models\Review::where('customer_id', $user->id)
                ->where('created_at', '>=', now()->subDays(30))
                ->count(),
        ];
        
        return view('customer.orders.rating-history', [
            'title' => 'My Rating History',
            'reviews' => $reviews,
            'stats' => $stats,
        ]);
    })->name('customer.rating.history');

// ====================
// EMPLOYEE PAGES
// ====================

Route::middleware(['auth.web', 'role.web:employee'])
    ->prefix('employee')
    ->name('employee.')
    ->group(function () {
    Route::get('/dashboard', function () {
        return view('employee.dashboard');
    })->name('dashboard');

        // Profile
        Route::get('/profile', [\App\Http\Controllers\Web\Auth\EmployeeAuthController::class, 'profile'])
            ->name('profile');
        Route::put('/profile', [\App\Http\Controllers\Web\Auth\EmployeeAuthController::class, 'updateProfile'])
            ->name('profile.update');

        // Orders Management
        Route::controller(\App\Http\Controllers\Web\Employee\OrderManagementController::class)
            ->prefix('orders')
            ->name('orders.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/filter', 'filterByDate')->name('filter.date');
                Route::get('/{id}', 'show')->name('show');
                Route::put('/{id}', 'update')->name('update');
                Route::put('/{id}/status', 'updateStatus')->name('update.status');
                Route::post('/{id}/ready', 'markAsReady')->name('ready');
                Route::post('/{id}/complete', 'markAsCompleted')->name('complete');
            });
            
        Route::controller(\App\Http\Controllers\Web\Employee\PaymentConfirmationController::class)
            ->prefix('payments')
            ->name('payments.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/{id}', 'show')->name('show');
                Route::put('/{id}/confirm', 'confirm')->name('confirm');
                Route::put('/{id}/validate', 'validatePayment')->name('validate');
                Route::post('/{id}/reject', 'reject')->name('reject');
                Route::post('/{id}/failed', 'markAsFailed')->name('failed');
            });

        // Receipts
        Route::controller(\App\Http\Controllers\Web\Employee\ReceiptController::class)
            ->prefix('receipts')
            ->name('receipts.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/{orderId}', 'show')->name('show');
                Route::get('/{orderId}/print', 'print')->name('print');
                Route::post('/{orderId}/email', 'email')->name('email');
                Route::get('/{orderId}/download', 'download')->name('download');
            });
    });

// ====================
// ADMIN PAGES
// ====================

Route::middleware(['auth.web', 'role.web:admin'])
    ->prefix('admin')
    ->name('admin.')
    ->group(function () {
        // Dashboard
        Route::get('/dashboard', [\App\Http\Controllers\Web\Admin\DashboardController::class, 'index'])
            ->name('dashboard');

        Route::get('/dashboard/data', [\App\Http\Controllers\Web\Admin\DashboardController::class, 'getDashboardData'])
            ->name('dashboard.data');

        // Profile
        Route::get('/profile', [\App\Http\Controllers\Web\Auth\AdminAuthController::class, 'profile'])
            ->name('profile');

        Route::put('/profile', [\App\Http\Controllers\Web\Auth\AdminAuthController::class, 'updateProfile'])
            ->name('profile.update');

        
        // Users Management (pindah ke AdminAuthController)
        Route::prefix('users')->name('users.')->group(function () {
            Route::get('/', [AdminAuthController::class, 'usersIndex'])->name('index');
            Route::get('/create', [AdminAuthController::class, 'createUser'])->name('create');
            Route::post('/', [AdminAuthController::class, 'storeUser'])->name('store');
            Route::get('/{id}', [AdminAuthController::class, 'showUser'])->name('show');
            Route::put('/{id}', [AdminAuthController::class, 'updateUser'])->name('update');
            Route::get('/users/{id}/edit', [AdminAuthController::class, 'editUser'])->name('users.edit');
            Route::delete('/{id}', [AdminAuthController::class, 'deleteUser'])->name('destroy');
        });

        // Menu Management
        Route::controller(\App\Http\Controllers\Web\Admin\MenuManagementController::class)
            ->prefix('menu')
            ->name('menu.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/edit', 'edit')->name('edit');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
                // Route::put('/{id}/toggle-availability', 'toggleAvailability')->name('toggle_availability');
            });

        // Promo Management
        Route::controller(\App\Http\Controllers\Web\Admin\PromoManagementController::class)
            ->prefix('promos')
            ->name('promos.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/edit', 'edit')->name('edit');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
                Route::put('/{id}/toggle-active', 'toggleActive')->name('toggle_active');
            });

        // Payment Methods
        Route::controller(\App\Http\Controllers\Web\Admin\PaymentMethodController::class)
            ->prefix('payment-methods')
            ->name('payment-methods.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/edit', 'edit')->name('edit');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
            });

        // Careers Management
        Route::controller(\App\Http\Controllers\Web\Admin\CareerManagementController::class)
            ->prefix('careers')
            ->name('careers.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::get('/create', 'create')->name('create');
                Route::post('/', 'store')->name('store');
                Route::get('/{id}', 'show')->name('show');
                Route::get('/{id}/edit', 'edit')->name('edit');
                Route::put('/{id}', 'update')->name('update');
                Route::delete('/{id}', 'destroy')->name('destroy');
            });

        // Career Applications
        Route::controller(\App\Http\Controllers\Web\Admin\CareerManagementController::class)
            ->prefix('career-applications')
            ->name('career-applications.')
            ->group(function () {
                Route::get('/', 'applications')->name('index');
                Route::get('/{id}', 'showApplication')->name('show');
                Route::put('/{id}/status', 'updateApplicationStatus')->name('status.update');
            });


        // System Settings
        Route::controller(\App\Http\Controllers\Web\Admin\SystemSettingController::class)
            ->prefix('settings')
            ->name('settings.')
            ->group(function () {
                Route::get('/', 'index')->name('index');
                Route::put('/general', 'updateGeneral')->name('general.update');
                Route::put('/operational-hours', 'updateOperationalHours')->name('operational-hours.update');
                Route::put('/tax', 'updateTax')->name('tax.update');
            });

        // Reports
        Route::controller(\App\Http\Controllers\Web\Admin\ReportController::class)
            ->prefix('reports')
            ->name('reports.')
            ->group(function () {
                Route::get('/sales', 'sales')->name('sales');
                Route::get('/finance', 'finance')->name('finance');
                Route::get('/performance', 'performance')->name('performance');
                Route::get('/orders/date-range', 'ordersByDateRange')->name('orders.date-range');
            });
    });

// ====================
// LOGOUT
// ====================

Route::post('/logout', [AuthController::class, 'logout'])->name('logout');

// ====================
// ERROR PAGES
// ====================

Route::view('/401', 'errors.401')->name('error.401');
Route::view('/403', 'errors.403')->name('error.403');
Route::view('/404', 'errors.404')->name('error.404');
Route::view('/500', 'errors.500')->name('error.500');

Route::fallback(function () {
    return view('errors.404');
});


// Debug routes
Route::get('/debug/user', function () {
    if (!Auth::check()) {
        return response()->json(['status' => 'not_logged_in']);
    }

    $user = Auth::user();
    return response()->json([
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email,
        'role' => $user->role,
        'role_from_db' => \App\Models\User::find($user->id)->role,
        'session_role' => session('user_role'),
        'is_logged_in' => session('is_logged_in')
    ]);
});

Route::get('/debug/fix-customer-role', function () {
    // Fix role for testing
    $user = Auth::user();
    if ($user) {
        $user->role = 'customer';
        $user->save();

        // Update session
        session()->put('user_role', 'customer');

        return redirect()->route('customer.dashboard')
            ->with('success', 'Role fixed to customer');
    }

    return redirect()->route('login');
});
