<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class InvoiceController extends Controller
{
    public function list()
    {
        $user = Auth::user();
        $query = Invoice::with(['user', 'transaction']);

        if ($user->role !== 'admin') {
            $query->where('user_id', $user->id);
        }

        $invoices = $query->orderBy('created_at', 'desc')->paginate(20);

        // Calculate statistics
        $statsQuery = Invoice::query();
        if ($user->role !== 'admin') {
            $statsQuery->where('user_id', $user->id);
        }

        $totalInvoices = $statsQuery->count();
        $paidInvoices = (clone $statsQuery)->where('status', 'paid')->count();
        $unpaidInvoices = (clone $statsQuery)->where('status', 'pending')->count();
        $totalAmount = (clone $statsQuery)->where('status', 'paid')->sum('total');

        return view('invoice-list', compact('invoices', 'totalInvoices', 'paidInvoices', 'unpaidInvoices', 'totalAmount'));
    }

    public function show($id)
    {
        $user = Auth::user();
        $invoice = Invoice::with(['user', 'transaction'])->findOrFail($id);

        if ($user->role !== 'admin' && $invoice->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        return view('invoice.show', compact('invoice'));
    }

    public function create()
    {
        return view('invoice.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:0',
            'tax' => 'nullable|numeric|min:0',
            'discount' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'invoice_type' => 'required|in:transaction,subscription,custom',
            'due_at' => 'nullable|date',
        ]);

        $user = Auth::user();
        $amount = $request->amount;
        $tax = $request->tax ?? 0;
        $discount = $request->discount ?? 0;
        $total = ($amount + $tax) - $discount;

        $invoice = Invoice::create([
            'user_id' => $user->id,
            'invoice_number' => Invoice::generateInvoiceNumber(),
            'invoice_type' => $request->invoice_type,
            'transaction_id' => $request->transaction_id,
            'amount' => $amount,
            'tax' => $tax,
            'discount' => $discount,
            'total' => $total,
            'currency' => $request->currency ?? 'USD',
            'status' => 'pending',
            'description' => $request->description,
            'items' => $request->items ? json_decode($request->items, true) : null,
            'issued_at' => now(),
            'due_at' => $request->due_at,
        ]);

        return redirect()->route('invoice.show', $invoice->id)
            ->with('success_alert', __('Invoice created successfully'));
    }

    public function generateFromTransaction($transactionId)
    {
        $user = Auth::user();
        $transaction = Transaction::findOrFail($transactionId);

        if ($user->role !== 'admin' && $transaction->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $existingInvoice = Invoice::where('transaction_id', $transactionId)->first();
        if ($existingInvoice) {
            return redirect()->route('invoice.show', $existingInvoice->id)
                ->with('info_alert', __('Invoice already exists for this transaction'));
        }

        $invoice = Invoice::create([
            'user_id' => $transaction->user_id,
            'invoice_number' => Invoice::generateInvoiceNumber(),
            'invoice_type' => 'transaction',
            'transaction_id' => $transaction->id,
            'amount' => $transaction->amount,
            'tax' => 0,
            'discount' => 0,
            'total' => $transaction->amount,
            'currency' => 'USD',
            'status' => $transaction->status === 'success' ? 'paid' : 'pending',
            'description' => $transaction->description ?? 'Transaction #' . $transaction->id,
            'issued_at' => now(),
            'paid_at' => $transaction->status === 'success' ? now() : null,
        ]);

        return redirect()->route('invoice.show', $invoice->id)
            ->with('success_alert', __('Invoice generated successfully'));
    }

    public function markAsPaid($id)
    {
        $user = Auth::user();
        $invoice = Invoice::findOrFail($id);

        if ($user->role !== 'admin') {
            abort(403, 'Only admins can mark invoices as paid');
        }

        $invoice->markAsPaid();

        return redirect()->back()
            ->with('success_alert', __('Invoice marked as paid'));
    }

    public function destroy($id)
    {
        $user = Auth::user();
        $invoice = Invoice::findOrFail($id);

        if ($user->role !== 'admin' && $invoice->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        $invoice->delete();

        return redirect()->route('invoice.list')
            ->with('success_alert', __('Invoice deleted successfully'));
    }

    public function download($id)
    {
        $user = Auth::user();
        $invoice = Invoice::with(['user', 'transaction'])->findOrFail($id);

        if ($user->role !== 'admin' && $invoice->user_id !== $user->id) {
            abort(403, 'Unauthorized access');
        }

        return view('invoice.pdf', compact('invoice'));
    }
}
