<?php

namespace App\Http\Controllers\Admin\Finance\Voucher;

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

class VoucherController extends Controller
{
    public function index($type, Request $request)
    {
        $query = Voucher::where('type', $type);

        if ($request->filled('start_date')) {
            $query->whereDate('voucher_date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('voucher_date', '<=', $request->end_date);
        }
        if ($request->filled('q')) {
            $q = $request->q;
            $query->where(function ($sub) use ($q) {
                $sub->where('voucher_number', 'like', "%$q%")
                    ->orWhere('description', 'like', "%$q%");
            });
        }

        $vouchers = $query->orderByDesc('voucher_date')->paginate(15)->appends($request->query());
        $title = ucwords(str_replace('-', ' ', $type)) . ' Vouchers';
        return view('admin.finance.vouchers.index', compact('vouchers', 'title', 'type'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'voucher_date' => 'required|date',
            'type' => 'required|string',
            'description' => 'required|string',
            'amount' => 'required|numeric|min:0',
        ]);

        Voucher::create($request->all() + [
            'voucher_number' => 'VCH-' . time(),
            'created_by' => auth()->id(),
        ]);

        return redirect()->back()->with('success', 'Voucher created successfully.');
    }

    public function update(Request $request, Voucher $voucher)
    {
        $request->validate([
            'voucher_date' => 'required|date',
            'description' => 'required|string',
            'amount' => 'required|numeric|min:0',
        ]);

        $voucher->update($request->all());

        return redirect()->back()->with('success', 'Voucher updated successfully.');
    }

    public function destroy(Voucher $voucher)
    {
        $voucher->delete();

        return redirect()->back()->with('success', 'Voucher deleted successfully.');
    }
}
