<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreVoucherRequest;
use App\Models\Voucher;
use App\Models\Account;
use App\Models\Party;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;

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

    public function index(Request $request)
    {
        $query = Voucher::with(['account', 'party', 'creator'])->latest('voucher_date');

        if ($from = $request->from_date) $query->whereDate('voucher_date', '>=', $from);
        if ($to = $request->to_date) $query->whereDate('voucher_date', '<=', $to);
        if ($type = $request->type) $query->where('type', $type);
        if ($account = $request->account_id) $query->where('account_id', $account);

        $vouchers = $query->paginate(20)->withQueryString();
        $totals = [
            'receipt' => (clone $query)->where('type', 'receipt')->sum('amount'),
            'payment' => (clone $query)->where('type', 'payment')->sum('amount'),
        ];
        return view('vouchers.index', compact('vouchers', 'totals'));
    }

    public function create(Request $request)
    {
        $type = $request->type ?? 'receipt';
        $accounts = Account::active()->orderBy('name')->get();
        $parties = $type === 'payment'
            ? Party::suppliers()->active()->orderBy('name')->get()
            : Party::customers()->active()->orderBy('name')->get();
        return view('vouchers.form', compact('type', 'accounts', 'parties'));
    }

    public function store(StoreVoucherRequest $request)
    {
        $service = app(\App\Services\AccountService::class);
        $method = $request->type === 'payment' ? 'createPayment' : 'createReceipt';
        $voucher = $service->$method($request->validated() + ['created_by' => auth()->id()]);
        $this->log->log('created', 'voucher', $voucher, "{$request->type} {$voucher->voucher_no} created");
        return redirect()->route('vouchers.show', $voucher->id)
            ->with('success', ucfirst($request->type) . " {$voucher->voucher_no} created.");
    }

    public function show(Voucher $voucher)
    {
        $voucher->load(['account', 'party', 'creator']);
        return view('vouchers.show', compact('voucher'));
    }

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

    public function restore($id)
    {
        $v = Voucher::onlyTrashed()->findOrFail($id);
        $v->restore();
        $this->log->log('restored', 'voucher', $v, "Voucher {$v->voucher_no} restored");
        return back()->with('success', "Voucher {$v->voucher_no} restored.");
    }
}
