<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreReturnRequest;
use App\Models\PurchaseReturn;
use App\Models\Party;
use App\Models\Purchase;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;

class PurchaseReturnController extends Controller
{
    public function __construct(protected ActivityLogService $log) {}

    public function index(Request $request)
    {
        $query = PurchaseReturn::with(['party', 'purchase', 'creator']);
        if ($from = $request->from_date) $query->whereDate('return_date', '>=', $from);
        if ($to = $request->to_date) $query->whereDate('return_date', '<=', $to);
        if ($party = $request->party_id) $query->where('party_id', $party);
        $returns = $query->latest('return_date')->paginate(20)->withQueryString();
        return view('purchase.return', compact('returns'));
    }

    public function create()
    {
        $suppliers = Party::suppliers()->active()->orderBy('name')->get();
        $purchases = Purchase::posted()->with('party')->latest('purchase_date')->get();
        return view('purchase.return-form', compact('suppliers', 'purchases'));
    }

    public function store(StoreReturnRequest $request)
    {
        $model = PurchaseReturn::create($request->validated() + ['created_by' => auth()->id()]);
        $this->log->log('created', 'purchase_return', $model, "Return {$model->voucher_no} created");
        return redirect()->route('purchase-return.show', $model->id)
            ->with('success', "Return {$model->voucher_no} created.");
    }

    public function show(PurchaseReturn $return)
    {
        $return->load(['party', 'purchase', 'creator']);
        return view('purchase.return-show', compact('return'));
    }

    public function edit(PurchaseReturn $return)
    {
        $suppliers = Party::suppliers()->active()->orderBy('name')->get();
        $purchases = Purchase::posted()->with('party')->latest('purchase_date')->get();
        return view('purchase.return-form', compact('return', 'suppliers', 'purchases'));
    }

    public function update(StoreReturnRequest $request, PurchaseReturn $return)
    {
        $old = $return->toArray();
        $return->update($request->validated());
        $this->log->log('updated', 'purchase_return', $return, "Return {$return->voucher_no} updated", $old, $return->toArray());
        return redirect()->route('purchase-return.show', $return->id)
            ->with('success', "Return {$return->voucher_no} updated.");
    }

    public function destroy(PurchaseReturn $return)
    {
        $vno = $return->voucher_no;
        $return->delete();
        $this->log->logAction('deleted', 'purchase_return', PurchaseReturn::class, $return->id, "Return {$vno} deleted");
        return redirect()->route('purchase-return.index')->with('success', "Return {$vno} deleted.");
    }
}
