<?php

use App\Http\Controllers\Auth\AuthOtpController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\BrandController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\OrderHistoryController as AdminOrderHistory;
use App\Http\Controllers\OrdersController;
use App\Http\Controllers\User\OrderHistoryController as UserOrderHistory;
use App\Http\Controllers\PosController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\ShippingCostController;
use App\Http\Controllers\User\UserCheckoutController;
use App\Http\Controllers\User\UserLandingController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\WarehouseController;

use Illuminate\Support\Facades\Route;

//Landing Page Routes
Route::get('/',[UserLandingController::class , 'index'])->name('home');

Route::get('/cart', [UserCheckoutController::class, "cartPage"])->name('cart');
Route::get('/search', function () {
    return view('search');
});

//Auth Routes
Route::get('/auth/login', [AuthController::class, "showLoginForm"])->name('login');
Route::post('/auth/login', [AuthController::class, "login"])->name('auth.login');
Route::get('/auth/register', [AuthController::class, "showRegisterForm"])->name('register');
Route::post('/auth/register', [AuthController::class, "register"])->name('auth.register');
Route::post ('/logout', [AuthController::class, "logout"])->name('logout');

// OTP Auth Routes
Route::post('/auth/request-otp', [AuthOtpController::class, "requestOtp"])->name('auth.request-otp');
Route::post('/auth/verify-otp', [AuthOtpController::class, "verifyOtp"])->name('auth.verify-otp');

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Product;
use App\Models\User;
use Illuminate\Support\Facades\DB;

Route::middleware('isAdmin')->group(function () {
    Route::get('/admin/dashboard', function () {
        $totalRevenue = Order::whereIn('status', ['paid', 'verify', 'dikirim'])->sum('total_amount');
        $totalOrders = Order::count();
        $totalProducts = Product::count();
        $totalCustomers = User::where('role', 'user')->count();

        $ordersByStatus = Order::selectRaw("status, COUNT(*) as count")
            ->groupBy('status')->pluck('count', 'status');

        $productsInStock = Product::where('stock', '>', 5)->count();
        $productsLowStock = Product::where('stock', '>', 0)->where('stock', '<=', 5)->count();

        $recentOrders = Order::with(['user', 'items.product'])
            ->latest()->take(5)->get();

        $topProducts = OrderItem::select('product_id', DB::raw('SUM(quantity) as total_qty'))
            ->whereHas('order', fn($q) => $q->whereIn('status', ['paid', 'verify', 'dikirim']))
            ->groupBy('product_id')->orderByDesc('total_qty')
            ->with('product')->take(5)->get();

        $salesDaily = Order::whereIn('status', ['paid', 'verify', 'dikirim'])
            ->whereBetween('created_at', [now()->startOfWeek(), now()->endOfWeek()])
            ->selectRaw("DATE(created_at) as date, SUM(total_amount) as total")
            ->groupBy('date')->pluck('total', 'date');

        return view('admin.dashboard', compact(
            'totalRevenue', 'totalOrders', 'totalProducts', 'totalCustomers',
            'ordersByStatus', 'productsInStock', 'productsLowStock',
            'recentOrders', 'topProducts', 'salesDaily'
        ));
    })->name('admin.dashboard');

    //brand
    Route::get('/admin/brands',[BrandController::class, "index"])->name('admin.brands.index');
    Route::delete('/admin/brands/{brand}', [BrandController::class, "destroy"])->name('admin.brands.destroy');
    Route::post('/admin/brands', [BrandController::class, "store"])->name('admin.brands.store');
    Route::put('/admin/brands/{brand}', [BrandController::class, "update"])->name('admin.brands.update');

    //category
    Route::get('/admin/categories',[CategoryController::class, "index"])->name('admin.categories.index');
    Route::delete('/admin/categories/{category}', [CategoryController::class, "destroy"])->name('admin.categories.destroy');
    Route::post('/admin/categories', [CategoryController::class, "store"])->name('admin.categories.store');
    Route::put('/admin/categories/{category}', [CategoryController::class, "update"])->name('admin.categories.update');

    //product
    Route::get('/admin/products', [ProductController::class, "index"])->name('admin.products');
    Route::delete('/admin/products/{product}', [ProductController::class, "destroy"])->name('admin.products.destroy');
    Route::post('/admin/products', [ProductController::class, "store"])->name('admin.products.store');
    Route::put('/admin/products/{product}', [ProductController::class, "update"])->name('admin.products.update');

    //shipping costs
    Route::get('/admin/shipping-costs', [ShippingCostController::class, "index"])->name('admin.shipping-costs.index');
    Route::post('/admin/shipping-costs', [ShippingCostController::class, "store"])->name('admin.shipping-costs.store');
    Route::put('/admin/shipping-costs/{shippingCost}', [ShippingCostController::class, "update"])->name('admin.shipping-costs.update');
    Route::delete('/admin/shipping-costs/{shippingCost}', [ShippingCostController::class, "destroy"])->name('admin.shipping-costs.destroy');

    //users management
    Route::prefix('/admin/users')->group(function () {
        Route::get('/', [UserController::class, "index"])->name('admin.users.index');
        Route::post('/', [UserController::class, "store"])->name('admin.users.store');
        Route::delete('/{user}', [UserController::class, "destroy"])->name('admin.users.destroy');
        Route::put('/{user}', [UserController::class, "update"])->name('admin.users.update');
    });

    //customers
    Route::prefix('/admin/customers')->group(function () {
        Route::get('/', [UserController::class, "customers"])->name('admin.customers.index');
        Route::post('/', [UserController::class, "store"])->name('admin.customers.store');
        Route::delete('/{user}', [UserController::class, "destroy"])->name('admin.customers.destroy');
        Route::put('/{user}', [UserController::class, "update"])->name('admin.customers.update');
    });

    //orders
    Route::prefix('/admin/orders')->group(function () {
        Route::get('/', [OrdersController::class, "index"])->name('admin.orders.index');
        Route::patch('/{order}/status', [OrdersController::class, "updateStatus"])->name('admin.orders.updateStatus');
        Route::post('/{order}/update-item', [OrdersController::class, "updateItem"])->name('admin.orders.updateItem');
    });

    //pos
    Route::prefix('/admin/pos')->group(function () {
        Route::get('/', [PosController::class, "index"])->name('admin.pos.index');
        Route::post('/add-to-cart', [PosController::class, "addToCart"])->name('admin.pos.add-to-cart');
        Route::post('/update-cart', [PosController::class, "updateCart"])->name('admin.pos.update-cart');
        Route::post('/remove-from-cart', [PosController::class, "removeFromCart"])->name('admin.pos.remove-from-cart');
        Route::post('/checkout', [PosController::class, "checkout"])->name('admin.pos.checkout');
        Route::post('/clear-cart', [PosController::class, "clearCart"])->name('admin.pos.clear-cart');
    });

    //reports
    Route::get('/admin/reports/sales', [ReportController::class, "sales"])->name('admin.reports.sales');
});

// Warehouse routes (admin + gudang)
Route::middleware('isGudang')->group(function () {
    Route::get('/warehouse', [WarehouseController::class, "index"])->name('admin.warehouse.index');
    Route::post('/warehouse/{order}/verify', [WarehouseController::class, "verify"])->name('admin.warehouse.verify');
    Route::post('/warehouse/{order}/send', [WarehouseController::class, "send"])->name('admin.warehouse.send');
});

Route::post('/checkout/process', [UserCheckoutController::class, "process"])->name('checkout.process');
Route::post('/payments/update-status', [UserCheckoutController::class, "updateStatus"])->name('payments.update-status');

Route::middleware('auth')->group(function () {
    Route::get('/orders', [UserOrderHistory::class, "myOrders"])->name('orders.my');
});
