<?php

use App\Http\Controllers\CartController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\OrderTrackingController;
use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ShopController;
use App\Models\Product;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Route;

Route::get('/migrate-secret-123', function () {
    Artisan::call('migrate', ['--force' => true]);

    return Artisan::output();
});

// Shop routes
Route::get('/', [ShopController::class, 'index'])->name('shop.index');
Route::get('/shop', [ShopController::class, 'products'])->name('shop.products');
Route::get('/category/{category}', [ShopController::class, 'category'])->name('shop.category');
Route::get('/product/{product}', [ShopController::class, 'product'])->name('shop.product');
Route::get('/search', [ShopController::class, 'search'])->name('shop.search');
Route::get('/featured-products', [ShopController::class, 'loadMoreFeatured'])->name('shop.featured.load');

// Blog routes
Route::get('/blogs', [App\Http\Controllers\BlogController::class, 'index'])->name('blogs.index');
Route::get('/blog/{blog}', [App\Http\Controllers\BlogController::class, 'show'])->name('blogs.show');
Route::get('/blog-category/{category}', [App\Http\Controllers\BlogController::class, 'category'])->name('blogs.category');

// Contact routes
Route::get('/contact', [App\Http\Controllers\ContactController::class, 'index'])->name('contact.index');
Route::post('/contact', [App\Http\Controllers\ContactController::class, 'store'])->name('contact.store');

// Cart routes
Route::prefix('cart')->name('cart.')->group(function () {
    Route::get('/', [CartController::class, 'index'])->name('index');
    Route::post('/add', [CartController::class, 'add'])->name('add');
    Route::post('/update', [CartController::class, 'update'])->name('update');
    Route::post('/remove', [CartController::class, 'remove'])->name('remove');
    Route::post('/update-services', [CartController::class, 'updateServices'])->name('update-services');
    Route::get('/product-services', [CartController::class, 'getProductServices'])->name('product-services');
    Route::post('/clear', [CartController::class, 'clear'])->name('clear');
    Route::get('/count', [CartController::class, 'count'])->name('count');
});

// Checkout routes
Route::prefix('checkout')->name('checkout.')->group(function () {
    Route::get('/', [CheckoutController::class, 'index'])->name('index');
    Route::get('/express', [CheckoutController::class, 'expressCheckout'])->name('express');
    Route::post('/process', [CheckoutController::class, 'process'])->name('process');
    Route::get('/verify-otp/{order}', [CheckoutController::class, 'showOrderOtp'])->name('verify-otp');
    Route::post('/verify-otp/{order}', [CheckoutController::class, 'verifyOrderOtp'])->name('verify-otp.submit');
    Route::post('/resend-otp/{order}', [CheckoutController::class, 'resendOrderOtp'])->name('resend-otp');

    Route::post('/send-checkout-otp', [CheckoutController::class, 'sendCheckoutOtp'])->name('send.otp');
    Route::post('/verify-checkout-otp', [CheckoutController::class, 'verifyCheckoutOtp'])->name('verify.otp');
});

// Phone lookup API
Route::get('/api/get-user-address', [CheckoutController::class, 'getUserAddress'])->name('api.get-user-address');

// Order success
Route::get('/order/{order}/success', [CheckoutController::class, 'success'])->name('order.success');

// Order tracking routes
Route::get('/track-order', [OrderTrackingController::class, 'index'])->name('order.tracking');
Route::post('/track-order', [OrderTrackingController::class, 'track'])->name('order.tracking.search');
Route::get('/track-order/{orderNumber}', [OrderTrackingController::class, 'show'])->middleware('auth')->name('order.tracking.details');
Route::get('/api/order/{orderNumber}/timeline', [OrderTrackingController::class, 'getStatusTimeline'])->middleware('auth')->name('order.timeline');

// AJAX Authentication routes
Route::post('/ajax/login', [App\Http\Controllers\Auth\OtpAuthController::class, 'sendOtp'])->name('ajax.login');
Route::post('/ajax/register', [App\Http\Controllers\Auth\OtpAuthController::class, 'sendOtp'])->name('ajax.register');
Route::post('/ajax/verify-otp', [App\Http\Controllers\Auth\OtpAuthController::class, 'verifyOtp'])->name('ajax.verify.otp');
Route::post('/ajax/resend-otp', [App\Http\Controllers\Auth\OtpAuthController::class, 'resendOtp'])->name('ajax.resend.otp');
Route::post('/ajax/auth/login', [App\Http\Controllers\Auth\PhoneLoginController::class, 'ajaxLogin'])->name('ajax.auth.login');

Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->middleware('auth')->name('dashboard');

// Customer order management routes
Route::middleware('auth')->group(function () {
    Route::patch('/orders/{order}/update', [App\Http\Controllers\DashboardController::class, 'updateOrder'])->name('orders.update');
    Route::patch('/orders/{order}/cancel', [App\Http\Controllers\DashboardController::class, 'cancelOrder'])->name('orders.cancel');

    // API routes for AJAX functionality
    Route::get('/api/orders/{order}/details', [App\Http\Controllers\DashboardController::class, 'getOrderDetails'])->name('api.orders.details');
    Route::get('/api/orders/{order}/edit-form', [App\Http\Controllers\DashboardController::class, 'getEditForm'])->name('api.orders.edit-form');
});

// Test routes for notification system
Route::get('/test-modal', function () {
    return view('test-modal');
})->name('test-modal');

Route::get('/test-notifications', function () {
    return view('test-notifications');
})->name('test-notifications');

Route::get('/test-password-change', function () {
    return view('test-password-change');
})->name('test-password-change');

// Debug route for cart session
Route::get('/debug-cart', function () {
    $sessionCart = session()->get('cart', []);

    return response()->json([
        'session_cart' => $sessionCart,
        'session_id' => session()->getId(),
        'auth_user' => auth()->user(),
    ]);
})->name('debug-cart');

// Test route for checkout controller
Route::get('/test-checkout', [CheckoutController::class, 'index'])->name('test-checkout');

// API routes for product quick view
Route::get('/api/products/{id}', function ($id) {
    try {
        $product = Product::with('category')->find($id);

        if (! $product) {
            return response()->json(['error' => 'Product not found'], 404);
        }

        $resolver = new \App\Services\ServicePriceResolver;
        $availableServices = $resolver->resolveServicesForProduct($id);
        $variants = $product->normalizedVariants();
        $selectedVariant = $product->defaultVariant();

        return response()->json([
            'id' => $product->id,
            'slug' => $product->slug,
            'name' => $product->name,
            'description' => $product->description,
            'short_description' => $product->short_description,
            'price' => $selectedVariant['final_price'] ?? $product->price,
            'base_unit_rate' => $selectedVariant['base_unit_price'] ?? $product->price,
            'unit' => $selectedVariant['unit'] ?? $product->unit,
            'selected_variant_index' => $selectedVariant['index'] ?? null,
            'selected_variant' => $selectedVariant,
            'variants' => $variants,
            'images' => $product->images ?? [],
            'features' => $product->features ?? [],
            'category' => $product->category ? [
                'id' => $product->category->id,
                'name' => $product->category->name,
            ] : null,
            'available_services' => $availableServices->map(fn ($item) => [
                'id' => $item['service']->id,
                'name' => $item['service']->name,
                'billing_type' => $item['service']->billing_type,
                'resolved_price' => $item['resolved_price'],
            ]),
        ]);
    } catch (\Exception $e) {
        \Log::error('API product error: '.$e->getMessage());

        return response()->json(['error' => 'Server error'], 500);
    }
})->name('api.product');

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';
require __DIR__.'/admin.php';
