<?php

use App\Http\Controllers\CustomerController;
use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\ReceiptController;
use App\Http\Controllers\SettingController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

// Login (gunakan Laravel Breeze/Jetstream atau bawaan)
Route::middleware('guest')->group(function () {
    Route::get('/login', fn() => view('auth.login'))->name('login');
    Route::post('/login', [App\Http\Controllers\Auth\AuthenticatedSessionController::class, 'store']);
});

Route::post('/logout', [App\Http\Controllers\Auth\AuthenticatedSessionController::class, 'destroy'])
    ->name('logout')
    ->middleware('auth');

// Semua route di bawah butuh login
Route::middleware('auth')->group(function () {

    // Dashboard
    Route::get('/', function () {
        $stats = [
            'total_invoices'   => \App\Models\Invoice::count(),
            'invoice_paid'     => \App\Models\Invoice::where('status', 'paid')->count(),
            'invoice_unpaid'   => \App\Models\Invoice::whereIn('status', ['draft', 'sent'])->count(),
            'total_receipts'   => \App\Models\Receipt::count(),
            'total_customers'  => \App\Models\Customer::count(),
            'revenue_month'    => \App\Models\Receipt::whereMonth('receipt_date', now()->month)->sum('amount_received'),
        ];
        $recent_invoices = \App\Models\Invoice::with('customer')->latest()->take(5)->get();
        return view('dashboard', compact('stats', 'recent_invoices'));
    })->name('dashboard');

    // Customers
    Route::resource('customers', CustomerController::class);

    // Invoices
    Route::resource('invoices', InvoiceController::class);
    Route::post('invoices/{invoice}/upload-assets', [InvoiceController::class, 'uploadAssets'])
        ->name('invoices.upload-assets');
    Route::get('invoices/{invoice}/print', [InvoiceController::class, 'print'])
        ->name('invoices.print');

    // Receipts (Tanda Terima)
    Route::resource('receipts', ReceiptController::class)->except(['edit', 'update']);
    Route::post('receipts/{receipt}/upload-assets', [ReceiptController::class, 'uploadAssets'])
        ->name('receipts.upload-assets');
    Route::get('receipts/{receipt}/print', [ReceiptController::class, 'print'])
        ->name('receipts.print');

    // Laporan
    Route::get('reports/invoices', [InvoiceController::class, 'report'])->name('reports.invoices');
    Route::get('reports/receipts', [ReceiptController::class, 'report'])->name('reports.receipts');

    // Settings
    Route::get('settings', [SettingController::class, 'index'])->name('settings.index');
    Route::post('settings', [SettingController::class, 'update'])->name('settings.update');

    // Users Management
    Route::post('users', [UserController::class, 'store'])->name('users.store');
    Route::delete('users/{user}', [UserController::class, 'destroy'])->name('users.destroy');
});