<?php

namespace App\Http\Controllers;

use App\Models\BankInvoice;
use App\Models\Buyer;
use App\Models\OrderConfirmation;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class BankInvoiceController extends Controller
{
    public function index()
    {
        $invoices = BankInvoice::with(['buyer', 'orderConfirmation', 'creator'])
            ->latest()
            ->paginate(20);

        return view('admin.payment.bank-invoices.index', compact('invoices'));
    }

    public function create()
    {
        $buyers = Buyer::all();
        
        $orders = OrderConfirmation::whereIn('status', ['confirmed', 'in_production'])->get();
        
        return view('admin.payment.bank-invoices.create', compact('buyers', 'orders'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'buyer_id' => 'required|exists:buyers,id',
            'order_confirmation_id' => 'required|exists:order_confirmations,id',
            'invoice_date' => 'required|date',
            'due_date' => 'required|date|after:invoice_date',
            'amount' => 'required|numeric|min:0.01',
            'tax_amount' => 'nullable|numeric|min:0',
            'description' => 'required|string|max:1000',
            'bank_remarks' => 'nullable|string',
        ]);

        $validated['created_by'] = auth()->id();
        BankInvoice::create($validated);

        return redirect()->route('admin.bank-invoices.index')
            ->with('success', 'Bank invoice created successfully.');
    }

    public function show(BankInvoice $bankInvoice)
    {
        $bankInvoice->load(['buyer', 'orderConfirmation', 'creator']);
        
        return view('admin.payment.bank-invoices.show', compact('bankInvoice'));
    }

    public function edit(BankInvoice $bankInvoice)
    {
        $buyers = Buyer::all();
        $orders = OrderConfirmation::whereIn('status', ['confirmed', 'in_production'])->get();
        
        return view('admin.payment.bank-invoices.edit', compact('bankInvoice', 'buyers', 'orders'));
    }

public function update(Request $request, BankInvoice $bankInvoice)
{
    $validated = $request->validate([
        'buyer_id' => 'required|exists:buyers,id',
        'order_confirmation_id' => 'required|exists:order_confirmations,id',
        'invoice_date' => 'required|date',
        'due_date' => 'required|date|after:invoice_date',
        'amount' => 'required|numeric|min:0.01',
        'tax_amount' => 'nullable|numeric|min:0',
        'description' => 'required|string|max:1000',
        'status' => 'required|in:draft,sent,paid,cancelled',
        'bank_remarks' => 'nullable|string',
    ]);

    $validated['total_amount'] = $validated['amount'] + ($validated['tax_amount'] ?? 0);

    $bankInvoice->update($validated);

    return redirect()->route('admin.bank-invoices.index')
        ->with('success', 'Bank invoice updated successfully.');
}
    public function destroy(BankInvoice $bankInvoice)
    {
        $bankInvoice->delete();

        return redirect()->route('admin.bank-invoices.index')
            ->with('success', 'Bank invoice deleted successfully.');
    }

    public function exportPdf(BankInvoice $bankInvoice)
    {
        $bankInvoice->load(['buyer', 'orderConfirmation']);
        
        $pdf = PDF::loadView('admin.payment.bank-invoices.export.pdf', compact('bankInvoice'));
        
        return $pdf->download("invoice-{$bankInvoice->invoice_number}.pdf");
    }

    public function markAsSent(BankInvoice $bankInvoice)
    {
        $bankInvoice->update(['status' => 'sent']);

        return back()->with('success', 'Invoice marked as sent to bank.');
    }

    public function markAsPaid(BankInvoice $bankInvoice)
    {
        $bankInvoice->update(['status' => 'paid']);

        return back()->with('success', 'Invoice marked as paid.');
    }
}