<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\InvoiceItem;
use App\Models\LegalCase;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf; // Import PDF facade
use Illuminate\Support\Str;
use App\Mail\InvoiceMailable;
use Illuminate\Support\Facades\Mail;
use App\Models\ActivityLog;

class InvoiceController extends Controller
{
    // 1. Show "Create Invoice" Form
    public function create(LegalCase $case)
    {
        return view('admin.invoices.create', compact('case'));
    }

    // 2. Store the Invoice
    public function store(Request $request, LegalCase $case)
    {
        $request->validate([
            'due_date' => 'required|date',
            'descriptions' => 'required|array',
            'amounts' => 'required|array',
        ]);

        // --- 1. Determine Status & Approval ---
        // Default: Pending Approval
        $status = 'pending_approval';
        $approvedBy = null;
        $approvedAt = null;

        // Check if current user is Head of Legal (Auto-approve if true)
        // Ensure you added the isHeadOfLegal() helper to your User model
        if (auth()->user()->isHeadOfLegal()) {
            $status = 'unpaid'; // Directly marked as ready for payment
            $approvedBy = auth()->id();
            $approvedAt = now();
        }

        // --- 2. Generate Invoice Number ---
        $invNum = 'INV-' . strtoupper(Str::random(6));

        // --- 3. Create Invoice Header ---
        $invoice = Invoice::create([
            'legal_case_id' => $case->id,
            'user_id' => auth()->id(), // Track creator
            'invoice_number' => $invNum,
            'due_date' => $request->due_date,
            'status' => $status,
            'total_amount' => 0, // Placeholder, calculated below
            'approved_by' => $approvedBy,
            'approved_at' => $approvedAt,
        ]);

        // --- 4. Process Items & Calculate Total ---
        $total = 0;

        foreach ($request->descriptions as $index => $desc) {
            $amount = $request->amounts[$index] ?? 0;

            if ($desc && $amount > 0) {
                InvoiceItem::create([
                    'invoice_id' => $invoice->id,
                    'description' => $desc,
                    'amount' => $amount,
                ]);
                $total += $amount;
            }
        }

        // --- 5. Update Final Total ---
        $invoice->update(['total_amount' => $total]);

        // --- 6. Contextual Success Message ---
        $message = ($status === 'pending_approval')
            ? 'Invoice submitted for approval.'
            : 'Invoice created and approved successfully.';

        return redirect()->route('admin.cases.show', $case->id)->with('success', $message);
    }

    // 3. Download PDF
    public function download($id)
    {
        $invoice = Invoice::with(['items', 'legalCase.client'])->findOrFail($id);

        $pdf = Pdf::loadView('admin.invoices.pdf', compact('invoice'));

        return $pdf->download($invoice->invoice_number . '.pdf');
    }

    public function edit(Invoice $invoice)
    {
        $invoice->load('items');
        $case = $invoice->legalCase;
        return view('admin.invoices.edit', compact('invoice', 'case'));
    }

    public function update(Request $request, Invoice $invoice)
    {
        $request->validate([
            'due_date' => 'required|date',
            'descriptions' => 'required|array',
            'amounts' => 'required|array',
        ]);

        // 1. Update Header
        $invoice->update([
            'due_date' => $request->due_date,
            'status' => $request->status,
        ]);

        // 2. Refresh Items (Delete and Re-add is the cleanest way for dynamic lists)
        $invoice->items()->delete();
        $total = 0;

        foreach ($request->descriptions as $index => $desc) {
            $amount = $request->amounts[$index];
            if ($desc && $amount) {
                $invoice->items()->create([
                    'description' => $desc,
                    'amount' => $amount,
                ]);
                $total += $amount;
            }
        }

        $invoice->update(['total_amount' => $total]);

        return redirect()->route('admin.cases.show', $invoice->legal_case_id)->with('success', 'Invoice updated.');
    }

    public function sendEmail(Invoice $invoice)
    {
        $clientEmail = $invoice->legalCase->client->email;

        Mail::to($clientEmail)->send(new InvoiceMailable($invoice));
        ActivityLog::record('Email', 'Invoice', "Sent Invoice #{$invoice->invoice_number} to client.");

        return back()->with('success', 'Invoice has been sent to ' . $clientEmail);
    }

    public function approve($id)
    {
        $invoice = Invoice::findOrFail($id);

        // Security check
        if (!auth()->user()->isHeadOfLegal()) {
            abort(403, 'Unauthorized action.');
        }

        $invoice->update([
            'status' => 'unpaid',
            'approved_by' => auth()->id(),
            'approved_at' => now(),
            'rejection_reason' => null
        ]);

        return back()->with('success', 'Invoice approved.');
    }

 
    public function reject(Request $request, $id)
    {
        $invoice = Invoice::findOrFail($id);

        if (!auth()->user()->isHeadOfLegal()) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate(['reason' => 'required|string']);

        $invoice->update([
            'status' => 'draft',
            'rejection_reason' => $request->reason,
            'approved_by' => null,
            'approved_at' => null
        ]);

        return back()->with('success', 'Invoice rejected.');
    }
}
