<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Bill;
use Illuminate\Http\Request;

class WebBillController extends Controller
{
    public function index(Request $request)
    {
        $query = Bill::with(['transportLoad', 'transportLoad.requester', 'transportLoad.driver']);

        // Search
        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('bill_number', 'like', "%{$search}%")
                  ->orWhere('transport_license_plate', 'like', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->has('status') && $request->status) {
            $query->where('status', $request->status);
        }

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->orWhereHas('transportLoad.requester', function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%");
            });
        }

        $bills = $query->orderBy('created_at', 'desc')->paginate(15);

        $totalBills = Bill::count();
        $paidBills = Bill::whereIn('status', ['delivered'])->count();
        $pendingBills = Bill::whereIn('status', ['issued', 'in_transit'])->count();
        $totalRevenue = Bill::sum('declared_value');

        return view('admin.bills.index', compact('bills', 'totalBills', 'paidBills', 'pendingBills', 'totalRevenue'));
    }

    public function show($id)
    {
        $bill = Bill::with(['transportLoad', 'transportLoad.requester', 'transportLoad.driver', 'cargoItems'])->findOrFail($id);

        return view('admin.bills.show', compact('bill'));
    }
}
