<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Sale;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class InvoiceController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $user = Auth::user();
        $query = Invoice::with(['sale', 'user']);
        
        $isAdmin = $user->role && $user->role->slug === 'admin';
        
        if (!$isAdmin) {
            $query->where('user_id', $user->id);
        }
        
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }
        
        if ($request->has('customer_name')) {
            $query->where('customer_name', 'like', "%{$request->customer_name}%");
        }
        
        if ($request->has('date_from')) {
            $query->where('issue_date', '>=', $request->date_from);
        }
        
        if ($request->has('date_to')) {
            $query->where('issue_date', '<=', $request->date_to);
        }
        
        $invoices = $query->orderBy('created_at', 'desc')->get();
        
        return response()->json([
            'invoices' => $invoices,
            'is_admin' => $isAdmin
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'sale_id' => 'required|exists:sales,id',
            'customer_name' => 'required|string|max:255',
            'customer_document' => 'nullable|string|max:50',
            'customer_address' => 'nullable|string',
            'customer_phone' => 'nullable|string|max:50',
            'customer_email' => 'nullable|email',
            'issue_date' => 'required|date',
            'due_date' => 'nullable|date',
            'notes' => 'nullable|string',
        ]);

        $sale = Sale::with('items.product')->findOrFail($validated['sale_id']);

        if ($sale->status !== 'completed') {
            return response()->json(['error' => 'Sale must be completed to generate invoice'], 400);
        }

        $existingInvoice = Invoice::where('sale_id', $validated['sale_id'])->first();
        if ($existingInvoice) {
            return response()->json(['error' => 'Invoice already exists for this sale'], 400);
        }

        $customerDocument = $validated['customer_document'] ?? $sale->customer_document;
        
        if (!empty($customerDocument)) {
            try {
                $customer = Customer::where('document_number', $customerDocument)->first();
                
                $customerName = $validated['customer_name'] ?? $sale->customer_name ?? 'Cliente final';
                $customerEmail = $validated['customer_email'] ?? $sale->customer_email ?? null;
                $customerPhone = $validated['customer_phone'] ?? $sale->customer_phone ?? null;
                $customerAddress = $validated['customer_address'] ?? $sale->customer_address ?? null;
                
                if (!$customer) {
                    $customer = Customer::create([
                        'name' => $customerName,
                        'document_type' => strlen($customerDocument) === 8 ? 'DNI' : (strlen($customerDocument) === 11 ? 'RUC' : null),
                        'document_number' => $customerDocument,
                        'email' => $customerEmail,
                        'phone' => $customerPhone,
                        'address' => $customerAddress,
                        'is_active' => true,
                    ]);
                } else {
                    $customer->update([
                        'document_number' => $customerDocument,
                        'email' => $customerEmail,
                        'phone' => $customerPhone,
                        'address' => $customerAddress,
                    ]);
                }
            } catch (\Exception $e) {
                // Silently fail - customer is optional
            }
        }

        $validated['user_id'] = Auth::id();
        $validated['invoice_number'] = 'INV-' . date('YmdHis');
        $validated['subtotal'] = $sale->subtotal;
        $validated['tax'] = $sale->tax;
        $validated['discount'] = $sale->discount;
        $validated['total'] = $sale->total;
        $validated['status'] = 'draft';

        $invoice = Invoice::create($validated);

        return response()->json($invoice->load(['sale', 'user']), 201);
    }

    public function show(string $id): JsonResponse
    {
        $invoice = Invoice::with(['sale.items.product', 'user'])->findOrFail($id);
        return response()->json($invoice);
    }

    public function update(Request $request, string $id): JsonResponse
    {
        $invoice = Invoice::findOrFail($id);
        
        if ($invoice->status === 'paid' || $invoice->status === 'cancelled') {
            return response()->json(['error' => 'Cannot update a paid or cancelled invoice'], 400);
        }

        $validated = $request->validate([
            'status' => 'sometimes|in:draft,issued,paid,cancelled',
            'customer_name' => 'sometimes|string|max:255',
            'customer_document' => 'sometimes|string|max:50',
            'customer_address' => 'nullable|string',
            'customer_phone' => 'nullable|string|max:50',
            'customer_email' => 'nullable|email',
            'issue_date' => 'sometimes|date',
            'due_date' => 'nullable|date',
            'notes' => 'nullable|string',
        ]);
        
        $invoice->update($validated);
        
        return response()->json($invoice->load(['sale', 'user']));
    }

    public function destroy(string $id): JsonResponse
    {
        $invoice = Invoice::findOrFail($id);
        
        if ($invoice->status === 'paid' || $invoice->status === 'cancelled') {
            return response()->json(['error' => 'Cannot delete a paid or cancelled invoice'], 400);
        }
        
        $invoice->delete();
        
        return response()->json(['message' => 'Invoice deleted successfully']);
    }

    public function issue(string $id): JsonResponse
    {
        $invoice = Invoice::findOrFail($id);
        
        if ($invoice->status !== 'draft') {
            return response()->json(['error' => 'Only draft invoices can be issued'], 400);
        }

        $invoice->update(['status' => 'issued']);
        
        return response()->json($invoice->load(['sale', 'user']));
    }

    public function paid(string $id): JsonResponse
    {
        $invoice = Invoice::findOrFail($id);
        
        if ($invoice->status !== 'issued') {
            return response()->json(['error' => 'Only issued invoices can be marked as paid'], 400);
        }

        $invoice->update(['status' => 'paid']);
        
        return response()->json($invoice->load(['sale', 'user']));
    }

    public function cancelInvoice(string $id): JsonResponse
    {
        $invoice = Invoice::findOrFail($id);
        
        if ($invoice->status === 'paid') {
            return response()->json(['error' => 'Cannot cancel a paid invoice'], 400);
        }

        $invoice->update(['status' => 'cancelled']);
        
        return response()->json($invoice->load(['sale', 'user']));
    }
}
