<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\ApiController;
use App\Http\Controllers\OrderController;

// Test route
Route::get('/test', function () {
    return 'Test page working!';
});




// Simple test route
Route::get('/simple', function () {
    try {
        $products = \App\Models\Product::all();
        $stamps = \App\Models\Stamp::all();
        return view('student.simple', compact('products', 'stamps'));
    } catch (\Exception $e) {
        return 'Database error: ' . $e->getMessage();
    }
});

// Minimal test route
Route::get('/minimal', function () {
    try {
        $products = \App\Models\Product::all();
        $stamps = \App\Models\Stamp::all();
        return view('student.minimal', compact('products', 'stamps'));
    } catch (\Exception $e) {
        return 'Database error: ' . $e->getMessage();
    }
});

// Test order form route
Route::get('/test-order', function () {
    try {
        $product = \App\Models\Product::first();
        $stamps = \App\Models\Stamp::all();
        return view('student.order-form', compact('product', 'stamps'));
    } catch (\Exception $e) {
        return 'Order form error: ' . $e->getMessage();
    }
});

// Student routes (public) - protected by shop status
Route::middleware(['shop.open'])->group(function () {
    Route::get('/', [StudentController::class, 'index'])->name('student.index');
    
    // Complete Order Flow Routes - MUST come before /order/{product} route
    Route::get('/order/stamps', function () {
        $product = \App\Models\Product::first();
        $size = 'medium';
        $studentName = 'Test Student';
        $textCharacters = ['T', 'E', 'S', 'T', '1', '2', '3', '4'];
        
        // Get stamps based on product and size
        $query = \App\Models\Stamp::query();
        $query->where('type', 'small'); // For medium bracelet
        $stamps = $query->get();
        
        return view('order.stamps', compact('product', 'size', 'studentName', 'textCharacters', 'stamps'));
    })->name('order.stamps');

    Route::post('/order/stamps', [OrderController::class, 'saveStamps'])->name('order.save-stamps');
    Route::get('/order/position', [OrderController::class, 'position'])->name('order.position');
    Route::post('/order/position', [OrderController::class, 'savePosition'])->name('order.save-position');
    Route::get('/order/preview', [OrderController::class, 'preview'])->name('order.preview');
    Route::post('/order/final-submit', [OrderController::class, 'submit'])->name('order.submit');
    Route::get('/order/confirm/{order}', [OrderController::class, 'confirm'])->name('order.confirm');

    // Student order form route - MUST come after specific routes
    Route::get('/order/{product}', [StudentController::class, 'showOrderForm'])->name('student.order-form');
    Route::post('/order/initial-submit', [StudentController::class, 'submitOrder'])->name('student.submit-order');
    Route::get('/order/confirmation/{order}', [StudentController::class, 'orderConfirmation'])->name('student.confirmation');

    // Bracelet unified customization route
    Route::get('/bracelet/customize', [StudentController::class, 'showBraceletCustomize'])->name('student.bracelet-customize');
    Route::post('/bracelet/submit', [StudentController::class, 'submitBracelet'])->name('student.submit-bracelet');

    // Keychain version selection and customization routes
    Route::get('/keychain/version', [StudentController::class, 'showKeychainVersion'])->name('student.keychain-version');
    Route::get('/keychain/customize', [StudentController::class, 'showKeychainCustomize'])->name('student.keychain-customize');
    Route::post('/keychain/submit', [StudentController::class, 'submitKeychain'])->name('student.submit-keychain');

    // Bookmark style selection and customization routes
    Route::get('/bookmark/style', [StudentController::class, 'showBookmarkStyle'])->name('student.bookmark-style');
    Route::get('/bookmark/customize', [StudentController::class, 'showBookmarkCustomize'])->name('student.bookmark-customize');
    Route::post('/bookmark/submit', [StudentController::class, 'submitBookmark'])->name('student.submit-bookmark');
});

// Admin Authentication Routes
Route::get('/admin/login', function () {
    if (auth()->check()) {
        return redirect()->route('admin.dashboard');
    }
    return view('auth.admin-login');
})->name('admin.login');

Route::post('/admin/login', function (Request $request) {
    $credentials = $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    $remember = $request->has('remember');

    if (Auth::attempt($credentials, $remember)) {
        // Check if the authenticated user is an admin
        if (Auth::user()->is_admin) {
            $request->session()->regenerate();
            return redirect()->intended('/admin/dashboard');
        } else {
            // User exists but is not an admin
            Auth::logout();
            return back()->withErrors([
                'email' => 'Access denied. Admin privileges required.',
            ]);
        }
    }

    return back()->withErrors([
        'email' => 'The provided credentials do not match our records.',
    ]);
})->name('admin.login.submit');

// Legacy auth routes for backwards compatibility
Route::get('/login', function () {
    return redirect()->route('admin.login');
})->name('login');

Route::post('/login', function (Request $request) {
    return redirect()->route('admin.login.submit');
});

Route::post('/logout', function (Request $request) {
    Auth::logout();
    $request->session()->invalidate();
    $request->session()->regenerateToken();
    return redirect()->route('admin.login');
})->name('logout');

// Admin routes (protected)
Route::middleware(['admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/dashboard', [AdminController::class, 'dashboard'])->name('dashboard');
    Route::get('/orders', [AdminController::class, 'orders'])->name('orders');
    Route::get('/orders/{order}', [AdminController::class, 'orderDetails'])->name('order-details');
    Route::post('/orders/{order}/complete', [AdminController::class, 'markCompleted'])->name('mark-completed');
    Route::post('/orders/{order}/pending', [AdminController::class, 'markPending'])->name('mark-pending');
    Route::delete('/orders/{order}/delete', [AdminController::class, 'deleteOrder'])->name('delete-order');
    Route::get('/products', [AdminController::class, 'products'])->name('products');
    Route::get('/stamps', [AdminController::class, 'stamps'])->name('stamps');
    Route::post('/toggle-shop', [AdminController::class, 'toggleShop'])->name('toggle-shop');
    
    // Device Fingerprint Management routes
    Route::get('/device-fingerprints', [AdminController::class, 'deviceFingerprints'])->name('device-fingerprints');
    Route::post('/device-fingerprints/{fingerprint}/clear', [AdminController::class, 'clearFingerprint'])->name('clear-fingerprint');
    Route::post('/device-fingerprints/clear-expired', [AdminController::class, 'clearExpiredFingerprints'])->name('clear-expired-fingerprints');
    Route::post('/device-fingerprints/clear-all', [AdminController::class, 'clearAllFingerprints'])->name('clear-all-fingerprints');
    
    // Admin-specific logout route
    Route::post('/logout', function (Request $request) {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect()->route('admin.login');
    })->name('logout');
});

// Debug route to verify order sorting
Route::get('/debug/order-sort', function () {
    $orders = \App\Models\Order::with('product')
        ->orderBy('created_at', 'desc')
        ->take(10)
        ->get(['id', 'student_name', 'created_at', 'status']);
    
    return response()->json([
        'message' => 'Orders sorted by created_at DESC (newest first)',
        'count' => $orders->count(),
        'orders' => $orders->map(function($order) {
            return [
                'id' => $order->id,
                'name' => $order->student_name,
                'product' => $order->product->name ?? 'N/A',
                'created' => $order->created_at->format('Y-m-d H:i:s'),
                'status' => $order->status
            ];
        })
    ]);
})->middleware(['admin']);

// API routes
Route::prefix('api')->name('api.')->group(function () {
    Route::get('/orders', [ApiController::class, 'getOrders'])->name('orders');
    Route::get('/stamps', [ApiController::class, 'getStamps'])->name('stamps');
    Route::get('/products', [ApiController::class, 'getProducts'])->name('products');
    Route::post('/preview', [ApiController::class, 'generatePreview'])->name('preview');
    Route::get('/new-orders', [ApiController::class, 'getNewOrders'])->name('new-orders');
});
