<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\{Invoice, InvoiceItem, Client, Payment, ActivityLog};
use App\Services\InvoiceService;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function __construct(private InvoiceService $service) {}

    public function index(Request $request)
    {
        $q = Invoice::with('client')->orderByDesc('issue_date');
        if ($request->status)   $q->where('status', $request->status);
        if ($request->division) $q->where('division', $request->division);
        if ($request->client_id) $q->where('client_id', $request->client_id);
        if ($request->month)    $q->where('billing_month', $request->month)->where('billing_year', $request->year ?? now()->year);
        $invoices = $q->paginate(20)->withQueryString();
        $clients  = Client::where('is_active',1)->orderBy('name')->get();
        return view('admin.invoices.index', compact('invoices','clients'));
    }

    public function create()
    {
        $clients = Client::where('is_active',1)->orderBy('name')->get();
        return view('admin.invoices.create', compact('clients'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'client_id'    => 'required|exists:clients,id',
            'division'     => 'required|in:JPN,FixLab,Havva',
            'type'         => 'required|in:maintenance,extra_visit,work_order,project,other',
            'issue_date'   => 'required|date',
            'due_date'     => 'required|date|after_or_equal:issue_date',
            'billing_month'=> 'nullable|integer|between:1,12',
            'billing_year' => 'nullable|integer',
            'tax_percent'  => 'nullable|numeric|min:0|max:100',
            'notes'        => 'nullable|string',
        ]);
        $items = $request->validate([
            'items'               => 'required|array|min:1',
            'items.*.description' => 'required|string',
            'items.*.qty'         => 'required|integer|min:1',
            'items.*.unit_price'  => 'required|numeric|min:0',
        ])['items'];

        $invoice = $this->service->create($data, $items, auth()->id());
        return redirect()->route('admin.invoices.show', $invoice)->with('success','Invoice berhasil dibuat.');
    }

    public function show(Invoice $invoice)
    {
        $invoice->load(['client','items','payments','createdBy']);
        return view('admin.invoices.show', compact('invoice'));
    }

    public function edit(Invoice $invoice)
    {
        $clients = Client::where('is_active',1)->orderBy('name')->get();
        $invoice->load('items');
        return view('admin.invoices.edit', compact('invoice','clients'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        if (!in_array($invoice->status,['draft'])) {
            return back()->withErrors(['status'=>'Hanya invoice draft yang bisa diedit.']);
        }
        $data = $request->validate([
            'due_date'    => 'required|date',
            'tax_percent' => 'nullable|numeric|min:0|max:100',
            'notes'       => 'nullable|string',
        ]);
        $invoice->update($data);
        // Update items
        $invoice->items()->delete();
        foreach ($request->items as $item) {
            $invoice->items()->create(['description'=>$item['description'],'qty'=>$item['qty'],'unit_price'=>$item['unit_price'],'total'=>$item['qty']*$item['unit_price']]);
        }
        $invoice->recalculate();
        return redirect()->route('admin.invoices.show', $invoice)->with('success','Invoice diperbarui.');
    }

    public function pdf(Invoice $invoice)
    {
        $path = $this->service->generatePdf($invoice);
        return response()->download($path, "Invoice_{$invoice->invoice_number}.pdf");
    }

    public function send(Request $request, Invoice $invoice)
    {
        $this->service->sendToClient($invoice);
        return back()->with('success','Invoice dikirim ke klien.');
    }

    public function recordPayment(Request $request, Invoice $invoice)
    {
        $data = $request->validate([
            'amount'           => 'required|numeric|min:1',
            'payment_date'     => 'required|date',
            'payment_method'   => 'nullable|string',
            'reference_number' => 'nullable|string',
            'notes'            => 'nullable|string',
        ]);
        $data['invoice_id']   = $invoice->id;
        $data['recorded_by']  = auth()->id();
        Payment::create($data);
        ActivityLog::log('invoice','payment',"Pembayaran dicatat untuk invoice #{$invoice->invoice_number}", $invoice);
        return back()->with('success','Pembayaran dicatat.');
    }

    public function destroy(Invoice $invoice)
    {
        if ($invoice->status === 'paid') return back()->withErrors(['status'=>'Invoice yang sudah lunas tidak bisa dihapus.']);
        $invoice->delete();
        return redirect()->route('admin.invoices.index')->with('success','Invoice dihapus.');
    }
}
