<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Partner;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class PartnerController extends Controller
{
    public function index()
    {
        $partners = Partner::withCount('requests')->latest()->paginate(20);

        return view('admin.partners.index', compact('partners'));
    }

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'in:laboratoire,clinique'],
            'address' => ['nullable', 'string', 'max:255'],
            'contact_person' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'email' => ['required', 'email', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        $partner = Partner::create([
            'name' => $data['name'],
            'type' => $data['type'],
            'address' => $data['address'] ?? null,
            'contact_person' => $data['contact_person'] ?? null,
            'phone' => $data['phone'] ?? null,
            'email' => $data['email'],
            'active' => true,
        ]);

        User::create([
            'name' => $data['contact_person'] ?? $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'role' => User::ROLE_PARTNER,
            'partner_id' => $partner->id,
            'phone' => $data['phone'] ?? null,
            'active' => true,
        ]);

        return redirect()->route('admin.partners.index')
            ->with('success', "Partenaire '{$partner->name}' cree avec succes. Identifiants envoyes : {$data['email']}");
    }

    public function toggleActive(Partner $partner)
    {
        $partner->update(['active' => ! $partner->active]);
        $partner->users()->update(['active' => $partner->active]);

        return back()->with('success', 'Statut du partenaire mis a jour.');
    }
}
