<?php

namespace App\Http\Controllers;

use App\Models\Challan;
use App\Models\Party;
use App\Models\Sale;
use Illuminate\Http\Request;

class ChallanController extends Controller
{
    public function index(Request $request)
    {
        $challans = Challan::with('party')
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->when($request->search, fn ($q) => $q->where('challan_no', 'like', "%{$request->search}%"))
            ->latest('challan_date')
            ->paginate(20)
            ->withQueryString();

        return view('challan.index', compact('challans'));
    }

    public function create()
    {
        $customers = Party::customers()->active()->orderBy('name')->get();

        return view('challan.create', compact('customers'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'party_id'     => 'required|exists:parties,id',
            'challan_date' => 'required|date',
            'vehicle_no'   => 'nullable|string|max:20',
            'driver_name'  => 'nullable|string|max:100',
            'driver_phone' => 'nullable|string|max:20',
            'transport'    => 'nullable|string|max:100',
            'remarks'      => 'nullable|string|max:500',
        ]);

        $challan = Challan::create($data);

        return redirect()
            ->route('challan.index')
            ->with('success', "Challan {$challan->challan_no} created.");
    }

    public function updateStatus(Challan $challan, Request $request)
    {
        $challan->update(['status' => $request->status]);

        if ($request->status === 'delivered') {
            $challan->update(['delivery_date' => today()]);
        }

        return back()->with('success', 'Status updated.');
    }

    public function print($id = null)
    {
        $challan = $id ? Challan::find($id) : Challan::latest()->first();
        if (! $challan) {
            return redirect()->route('challan.index')->with('error', 'No challan found to print.');
        }
        $challan->load(['party', 'sale']);
        return view('challan.print', compact('challan'));
    }
}
