<?php

namespace App\Http\Controllers;

use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ClientController extends Controller
{
    public function index(Request $request)
    {
        $user  = Auth::user();
        $query = $user->clients()->withCount('invoices')
                      ->withSum('invoices', 'total');

        if ($request->filled('search')) {
            $s = $request->search;
            $query->where(function ($q) use ($s) {
                $q->where('name', 'like', "%{$s}%")
                  ->orWhere('business_name', 'like', "%{$s}%")
                  ->orWhere('email', 'like', "%{$s}%");
            });
        }

        $clients = $query->orderBy('name')->paginate(15)->withQueryString();

        return view('clients.index', compact('clients'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'          => ['required', 'string', 'max:150'],
            'email'         => ['nullable', 'email', 'max:150'],
            'phone'         => ['nullable', 'string', 'max:20'],
            'business_name' => ['nullable', 'string', 'max:150'],
            'address'       => ['nullable', 'string', 'max:500'],
        ]);

        $client = Auth::user()->clients()->create($data);

        return redirect()->route('clients.show', $client)
            ->with('success', "Client {$client->name} added successfully.");
    }

    public function show(Client $client)
    {
        $this->authorizeClient($client);

        $invoices = $client->invoices()
            ->latest()
            ->paginate(10);

        $stats = [
            'total_invoices' => $client->invoices()->count(),
            'total_paid'     => $client->invoices()->where('status', 'paid')->sum('total'),
            'total_unpaid'   => $client->invoices()->whereIn('status', ['sent','viewed','overdue'])->sum('total'),
            'total_overdue'  => $client->invoices()->where('status', 'overdue')->sum('total'),
        ];

        return view('clients.show', compact('client', 'invoices', 'stats'));
    }

    public function edit(Client $client)
    {
        $this->authorizeClient($client);
        return view('clients.edit', compact('client'));
    }

    public function update(Request $request, Client $client)
    {
        $this->authorizeClient($client);

        $data = $request->validate([
            'name'          => ['required', 'string', 'max:150'],
            'email'         => ['nullable', 'email', 'max:150'],
            'phone'         => ['nullable', 'string', 'max:20'],
            'business_name' => ['nullable', 'string', 'max:150'],
            'address'       => ['nullable', 'string', 'max:500'],
        ]);

        $client->update($data);

        return redirect()->route('clients.show', $client)
            ->with('success', 'Client updated successfully.');
    }

    public function destroy(Client $client)
    {
        $this->authorizeClient($client);

        if ($client->hasInvoices()) {
            return back()->with('error',
                'This client has invoices and cannot be deleted. Cancel or delete their invoices first.');
        }

        $name = $client->name;
        $client->delete();

        return redirect()->route('clients.index')
            ->with('success', "{$name} has been deleted.");
    }

    private function authorizeClient(Client $client): void
    {
        if ($client->user_id !== Auth::id()) {
            abort(403, 'Unauthorized');
        }
    }
}
