<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ClientController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $this->authorize('viewAny', \App\Models\Client::class);
        $clients = \App\Models\Client::latest()->paginate(10);
        return view('clients.index', compact('clients'));
    }

    public function create()
    {
        $this->authorize('create', \App\Models\Client::class);
        return view('clients.form');
    }

    public function store(Request $request)
    {
        $this->authorize('create', \App\Models\Client::class);
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'document_number' => 'nullable|string|max:50|unique:clients',
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'credit_limit' => 'required|numeric|min:0'
        ]);

        \App\Models\Client::create($validated);

        return redirect()->route('clients.index')->with('success', 'Cliente registrado exitosamente.');
    }

    public function show(string $id)
    {
        // View specific client sales/debts could go here
    }

    public function edit(string $id)
    {
        $client = \App\Models\Client::findOrFail($id);
        $this->authorize('update', $client);
        return view('clients.form', compact('client'));
    }

    public function update(Request $request, string $id)
    {
        $client = \App\Models\Client::findOrFail($id);
        $this->authorize('update', $client);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'document_number' => 'nullable|string|max:50|unique:clients,document_number,' . $id,
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'credit_limit' => 'required|numeric|min:0',
            'credit_balance' => 'numeric|min:0' // In case admins reset debt
        ]);

        $client->update($validated);

        return redirect()->route('clients.index')->with('success', 'Cliente actualizado exitosamente.');
    }

    public function destroy(string $id)
    {
        $client = \App\Models\Client::findOrFail($id);
        $this->authorize('delete', $client);
        // Ensure no debt or sales if deleting, or just soft delete.
        // For now, pure delete since this is MVP.
        $client->delete();

        return redirect()->route('clients.index')->with('success', 'Cliente eliminado.');
    }
}
