<?php

namespace App\Modules\FINANCE\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\FINANCE\Models\CreditNote;
use App\Modules\FINANCE\Models\Invoice;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CreditNoteController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = CreditNote::with(['invoice.client']);

            return DataTables::of($query)
                ->addIndexColumn()
                ->addColumn('invoice', fn($row) => $row->invoice?->invoice_number ?? '-')
                ->addColumn('client', fn($row) => $row->invoice?->client?->name ?? '-')
                ->editColumn('credit_note_date', fn($row) => $row->credit_note_date?->format('d M Y') ?? '-')
                ->editColumn('total_amount', fn($row) => number_format($row->total_amount, 2))
                ->editColumn('status', function($row) {
                    $class = $row->status === 'open' ? 'bg-info' : 'bg-secondary';
                    return '<span class="badge '.$class.'">'.ucfirst($row->status).'</span>';
                })
                ->addColumn('action', function($row) {
                    return view('finance::credit_notes.partials.actions', compact('row'))->render();
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('finance::credit_notes.index');
    }

    public function create()
    {
        $invoices = Invoice::with(['client', 'currency'])
            ->whereNotIn('status', ['voided'])
            ->where('balance_amount', '>', 0)
            ->orderByDesc('invoice_date')
            ->get();
        return view('finance::credit_notes.create', compact('invoices'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'invoice_id'       => 'required|exists:finance_invoices,id',
            'total_amount'     => 'required|numeric|min:0.01',
            'credit_note_date' => 'required|date',
        ]);

        $invoice = Invoice::findOrFail($request->invoice_id);

        $creditNote = CreditNote::create([
            'company_id'       => $invoice->company_id,
            'invoice_id'       => $request->invoice_id,
            'client_id'        => $invoice->client_id,
            'amount'           => $request->total_amount,
            'reason'           => $request->reason ?? $request->reason_type,
            'status'           => 'open',
        ]);

        return response()->json([
            'status'  => true,
            'message' => 'Credit note created successfully',
            'id'      => $creditNote->id,
        ]);
    }

    public function show(CreditNote $creditNote)
    {
        $creditNote->load(['client', 'invoice.client', 'invoice.currency']);
        return view('finance::credit_notes.show', compact('creditNote'));
    }

    public function destroy(CreditNote $creditNote)
    {
        $creditNote->delete();
        return response()->json(['status' => true, 'message' => 'Credit note deleted successfully']);
    }
}
