<?php
namespace App\Controllers;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Core\Permission;
use App\Models\Family;

final class FamilyController extends Controller
{
    public function index(): void
    {
        Auth::requireLogin();
        Permission::require('familles.view');

        $query = trim($_GET['q'] ?? '');

        $this->view('families/index', [
            'pageTitle' => 'Familles',
            'families' => Family::search($query),
            'query' => $query,
        ]);
    }

    public function create(): void
    {
        Auth::requireLogin();
        Permission::require('familles.create');

        $this->view('families/form', [
            'pageTitle' => 'Nouvelle famille',
            'family' => null,
            'responsible' => null,
            'formAction' => '/public/familles',
            'submitLabel' => 'Créer la famille',
        ]);
    }

    public function store(): void
    {
        Auth::requireLogin();
        Permission::require('familles.create');
        Csrf::verify($_POST['_csrf'] ?? null);

        [$family, $responsible, $errors] = $this->validatedData();

        if (Family::duplicateExists(
            $family['nom_famille'],
            $family['email_principal'],
            $family['telephone_principal']
        )) {
            $errors[] = 'Une famille portant ce nom avec le même e-mail ou téléphone existe déjà.';
        }

        if ($errors) {
            $_SESSION['form_errors'] = $errors;
            $_SESSION['old'] = $_POST;
            $this->redirect('/familles/nouveau');
        }

        $family['organisation_id'] = (int)(Auth::user()['organisation_id'] ?? 1);
        $id = Family::create($family, $responsible, (int)Auth::id());

        $_SESSION['success'] = 'La famille a été créée avec succès.';
        $this->redirect('/familles/voir?id=' . $id);
    }

    public function show(): void
    {
        Auth::requireLogin();
        Permission::require('familles.view');

        $id = (int)($_GET['id'] ?? 0);
        $family = Family::find($id);

        if (!$family) {
            http_response_code(404);
            exit('Famille introuvable.');
        }

        $this->view('families/show', [
            'pageTitle' => 'Dossier famille',
            'family' => $family,
            'responsible' => Family::responsible($id),
            'members' => Family::members($id),
        ]);
    }

    public function edit(): void
    {
        Auth::requireLogin();
        Permission::require('familles.edit');

        $id = (int)($_GET['id'] ?? 0);
        $family = Family::find($id);

        if (!$family) {
            http_response_code(404);
            exit('Famille introuvable.');
        }

        $this->view('families/form', [
            'pageTitle' => 'Modifier la famille',
            'family' => $family,
            'responsible' => Family::responsible($id),
            'formAction' => '/public/familles/modifier?id=' . $id,
            'submitLabel' => 'Enregistrer les modifications',
        ]);
    }

    public function update(): void
    {
        Auth::requireLogin();
        Permission::require('familles.edit');
        Csrf::verify($_POST['_csrf'] ?? null);

        $id = (int)($_GET['id'] ?? 0);
        if (!Family::find($id)) {
            http_response_code(404);
            exit('Famille introuvable.');
        }

        [$family, $responsible, $errors] = $this->validatedData();

        if (Family::duplicateExists(
            $family['nom_famille'],
            $family['email_principal'],
            $family['telephone_principal'],
            $id
        )) {
            $errors[] = 'Une autre famille avec ces coordonnées existe déjà.';
        }

        if ($errors) {
            $_SESSION['form_errors'] = $errors;
            $_SESSION['old'] = $_POST;
            $this->redirect('/familles/modifier?id=' . $id);
        }

        Family::update($id, $family, $responsible, (int)Auth::id());

        $_SESSION['success'] = 'Le dossier famille a été mis à jour.';
        $this->redirect('/familles/voir?id=' . $id);
    }

    private function validatedData(): array
    {
        $name = mb_strtoupper(trim($_POST['nom_famille'] ?? ''), 'UTF-8');
        $email = mb_strtolower(trim($_POST['email_principal'] ?? ''), 'UTF-8');
        $phone = trim($_POST['telephone_principal'] ?? '');
        $errors = [];

        if ($name === '') $errors[] = 'Le nom de la famille est obligatoire.';
        if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'L’adresse e-mail principale n’est pas valide.';
        }

        $family = [
            'nom_famille' => $name,
            'adresse_ligne1' => trim($_POST['adresse_ligne1'] ?? ''),
            'adresse_ligne2' => trim($_POST['adresse_ligne2'] ?? ''),
            'code_postal' => trim($_POST['code_postal'] ?? ''),
            'ville' => mb_strtoupper(trim($_POST['ville'] ?? ''), 'UTF-8'),
            'pays' => trim($_POST['pays'] ?? 'France'),
            'telephone_principal' => $phone,
            'telephone_secondaire' => trim($_POST['telephone_secondaire'] ?? ''),
            'email_principal' => $email,
            'email_secondaire' => mb_strtolower(trim($_POST['email_secondaire'] ?? ''), 'UTF-8'),
            'situation_familiale' => trim($_POST['situation_familiale'] ?? ''),
            'quotient_familial' => trim($_POST['quotient_familial'] ?? ''),
            'autorise_contact_telephone' => isset($_POST['autorise_contact_telephone']) ? 1 : 0,
            'autorise_contact_email' => isset($_POST['autorise_contact_email']) ? 1 : 0,
            'autorise_contact_sms' => isset($_POST['autorise_contact_sms']) ? 1 : 0,
            'rgpd_accepte' => isset($_POST['rgpd_accepte']) ? 1 : 0,
            'notes' => trim($_POST['notes'] ?? ''),
        ];

        $responsible = [
            'civilite' => $_POST['responsable_civilite'] ?? 'Non renseigne',
            'nom' => mb_strtoupper(trim($_POST['responsable_nom'] ?? ''), 'UTF-8'),
            'prenom' => self::formatFirstName(trim($_POST['responsable_prenom'] ?? '')),
            'lien' => trim($_POST['responsable_lien'] ?? ''),
            'autorite_parentale' => isset($_POST['responsable_autorite_parentale']) ? 1 : 0,
            'payeur_principal' => isset($_POST['responsable_payeur_principal']) ? 1 : 0,
            'telephone' => trim($_POST['responsable_telephone'] ?? ''),
            'email' => mb_strtolower(trim($_POST['responsable_email'] ?? ''), 'UTF-8'),
        ];

        if ($responsible['email'] !== '' && !filter_var($responsible['email'], FILTER_VALIDATE_EMAIL)) {
            $errors[] = 'L’adresse e-mail du responsable n’est pas valide.';
        }

        return [$family, $responsible, $errors];
    }

    private static function formatFirstName(string $value): string
    {
        return mb_convert_case(mb_strtolower($value, 'UTF-8'), MB_CASE_TITLE, 'UTF-8');
    }
}
