<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Package;
use App\Models\User;
use Illuminate\Http\Request;

class InvoiceController extends Controller
{
    public function index(Request $request)
    {
        $query = Invoice::with('user', 'package');
        if ($status = $request->get('status')) {
            $query->where('status', $status);
        }
        $invoices = $query->latest()->paginate(20);
        return view('admin.invoices.index', compact('invoices'));
    }

    public function create()
    {
        $users    = User::whereIn('role', ['user', 'reseller'])->orderBy('name')->get();
        $packages = Package::where('is_active', true)->orderBy('price')->get();
        return view('admin.invoices.create', compact('users', 'packages'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'user_id'    => 'required|exists:users,id',
            'package_id' => 'nullable|exists:packages,id',
            'amount'     => 'required|numeric|min:0',
            'currency'   => 'required|string|max:5',
            'due_date'   => 'nullable|date',
            'notes'      => 'nullable|string',
        ]);
        $data['status'] = 'unpaid';
        Invoice::create($data);
        return redirect()->route('admin.invoices.index')->with('success', 'Invoice created.');
    }

    public function show(Invoice $invoice)
    {
        $invoice->load('user', 'package', 'payments');
        return view('admin.invoices.show', compact('invoice'));
    }

    public function markPaid(Invoice $invoice)
    {
        $invoice->update([
            'status'         => 'paid',
            'paid_at'        => now(),
            'payment_method' => $invoice->payment_method ?? 'manual',
        ]);

        // If package linked, give the user blog quota (only resellers benefit)
        if ($invoice->package_id && $invoice->user) {
            $package = $invoice->package;
            $user = $invoice->user;
            if ($user->isReseller() && $package) {
                $user->increment('blogs_quota', $package->blogs_count);
            }
        }
        return back()->with('success', 'Invoice marked as paid.');
    }

    public function markUnpaid(Invoice $invoice)
    {
        $invoice->update(['status' => 'unpaid', 'paid_at' => null]);
        return back()->with('success', 'Invoice marked as unpaid.');
    }

    public function destroy(Invoice $invoice)
    {
        $invoice->delete();
        return back()->with('success', 'Invoice deleted.');
    }
}
