<?php

use App\Http\Controllers\AuthController;
use App\Http\Controllers\CategoryController;
use App\Http\Controllers\CustomerController;
use App\Http\Controllers\CustomerPaymentController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\PurchaseController;
use App\Http\Controllers\ReportController;
use App\Http\Controllers\SupplierController;
use App\Http\Controllers\SupplierPaymentController;
use App\Http\Controllers\WeightController;
use Illuminate\Support\Facades\Route;

// Auth
Route::get('login', [AuthController::class, 'showLogin'])->name('login');
Route::post('login', [AuthController::class, 'login'])->name('login.submit');
Route::post('logout', [AuthController::class, 'logout'])->name('logout');

// All protected routes
Route::middleware('auth')->group(function () {
    Route::get('/', [DashboardController::class, 'index'])->name('dashboard');

    Route::resource('categories', CategoryController::class)->except(['show']);
    Route::resource('weights', WeightController::class)->except(['show']);
    Route::resource('products', ProductController::class)->except(['show']);
    Route::resource('customers', CustomerController::class)->except(['destroy']);
    Route::resource('orders', OrderController::class);
    Route::resource('suppliers', SupplierController::class)->except(['destroy']);
    Route::resource('purchases', PurchaseController::class)->only(['index', 'create', 'store', 'show']);

    Route::get('suppliers/{supplier}/pay', [SupplierPaymentController::class, 'create'])->name('suppliers.pay');
    Route::post('suppliers/{supplier}/pay', [SupplierPaymentController::class, 'store'])->name('suppliers.pay.store');

    Route::get('customers/{customer}/pay', [CustomerPaymentController::class, 'create'])->name('customers.pay');
    Route::post('customers/{customer}/pay', [CustomerPaymentController::class, 'store'])->name('customers.pay.store');

    // Reports
    Route::get('reports', [ReportController::class, 'index'])->name('reports.index');
    Route::get('reports/daily', [ReportController::class, 'dailySummary'])->name('reports.daily');
    Route::get('reports/sales', [ReportController::class, 'salesLedger'])->name('reports.sales');
    Route::get('reports/supplier', [ReportController::class, 'supplierLedger'])->name('reports.supplier');
    Route::get('reports/customer', [ReportController::class, 'customerLedger'])->name('reports.customer');

    // API
    Route::get('api/products-by-category/{category}', function (App\Models\Category $category) {
        return $category->products()->with('weight')->get()->map(fn($p) => [
            'id' => $p->id,
            'weight_label' => $p->weight->label ?? '-',
            'price' => $p->price,
            'stock' => $p->stock,
        ]);
    });
});
