<?php

namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\Contact;
use App\Models\Customer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CustomerController extends Controller
{
    public function store(Request $request)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous n\'êtes pas autorisé à créer un client.');
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['required', 'string', 'max:20'],
        ]);

        try {
            DB::beginTransaction();

            // Create contact first
            $contact = Contact::create([
                'phone' => $validated['phone'],
                'email' => null,
            ]);

            // Create address
            $address = Address::create();

            // Create customer
            $customer = Customer::create([
                'contact_id' => $contact->id,
                'address_id' => $address->id,
                'name' => $validated['name'],
                'slug' => Str::slug($validated['name']),
                'status' => Customer::STATUS_INACTIVE,
                'notes' => null,
            ]);

            DB::commit();

            return redirect()->route('customers.edit', $customer)->with('success', 'Client créé avec succès!');
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);

            return back()->with('error', 'Erreur lors de la création du client: '.$e->getMessage());
        }
    }

    public function update(Request $request, Customer $customer)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous n\'êtes pas autorisé à modifier un client.');
        }

        // No merchant filtering needed for single-tenant app

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'notes' => ['nullable', 'string', 'max:1000'],
            'status' => ['required', 'in:0,1'],
        ]);

        try {
            $customer->update([
                'name' => $validated['name'],
                'slug' => Str::slug($validated['name']),
                'notes' => $validated['notes'],
                'status' => $validated['status'],
            ]);

            return back()->with('success', 'Client modifié avec succès!');
        } catch (\Exception $e) {
            report($e);

            return back()->with('error', 'Erreur lors de la modification du client: '.$e->getMessage());
        }
    }

    public function activate(Customer $customer)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous n\'êtes pas autorisé à activer un client.');
        }

        // No merchant filtering needed for single-tenant app

        try {
            $customer->update(['status' => Customer::STATUS_ACTIVE]);

            return back()->with('success', 'Client activé avec succès!');
        } catch (\Exception $e) {
            report($e);

            return back()->with('error', 'Erreur lors de l\'activation du client: '.$e->getMessage());
        }
    }

    public function deactivate(Customer $customer)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous n\'êtes pas autorisé à désactiver un client.');
        }

        // No merchant filtering needed for single-tenant app

        try {
            $customer->update(['status' => Customer::STATUS_INACTIVE]);

            return back()->with('success', 'Client désactivé avec succès!');
        } catch (\Exception $e) {
            report($e);

            return back()->with('error', 'Erreur lors de la désactivation du client: '.$e->getMessage());
        }
    }

    public function destroy(Customer $customer)
    {
        if (Auth::user()->role !== 'owner' && Auth::user()->role !== 'admin') {
            return back()->with('error', 'Vous n\'êtes pas autorisé à supprimer un client.');
        }

        // No merchant filtering needed for single-tenant app

        try {
            DB::beginTransaction();

            // Soft delete the customer
            $customer->delete();

            DB::commit();

            return redirect()->route('customers.index')->with('success', 'Client supprimé avec succès!');
        } catch (\Exception $e) {
            DB::rollBack();
            report($e);

            return back()->with('error', 'Erreur lors de la suppression du client: '.$e->getMessage());
        }
    }
}
