<?php

require_once __DIR__ . '/../Services/AdoptionService.php';

class AdoptionsController
{
    public static function store(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            header('Location: /animals');
            exit();
        }

        $animalId = (int) ($_POST['animal_id'] ?? 0);
        $name = trim($_POST['adopter_name'] ?? '');

        if (!$animalId || $name === '') {
            header('Location: /animal/show?id=' . $animalId);
            exit();
        }

        $data = [
            'animal_id' => $animalId,
            'adopter_name' => $name,
            'adopter_phone' => trim($_POST['adopter_phone'] ?? ''),
            'adopter_email' => trim($_POST['adopter_email'] ?? ''),
            'adopter_address' => trim($_POST['adopter_address'] ?? ''),
            'adopter_postal_code' => trim($_POST['adopter_postal_code'] ?? ''),
            'adopter_city' => trim($_POST['adopter_city'] ?? ''),
            'adoption_date' => $_POST['adoption_date'] ?? date('Y-m-d'),
            'notes' => trim($_POST['notes'] ?? ''),
        ];

        $db = DB::pdo();
        $contactId = (int) ($_POST['adopter_contact_id'] ?? 0);
        $contactData = [
            ':name' => $data['adopter_name'],
            ':phone' => $data['adopter_phone'] ?: null,
            ':email' => $data['adopter_email'] ?: null,
            ':address' => $data['adopter_address'] ?: null,
            ':postal' => $data['adopter_postal_code'] ?: null,
            ':city' => $data['adopter_city'] ?: null,
        ];
        if ($contactId > 0) {
            $contactData[':id'] = $contactId;
            $db->prepare(
                "UPDATE directory_contacts SET name=:name,phone=:phone,email=:email,address=:address,postal_code=:postal,city=:city,updated_at=datetime('now') WHERE id=:id AND deleted_at IS NULL",
            )->execute($contactData);
        } else {
            $db->prepare(
                "INSERT INTO directory_contacts(kind,name,phone,email,address,postal_code,city) VALUES('person',:name,:phone,:email,:address,:postal,:city)",
            )->execute($contactData);
            $contactId = (int) $db->lastInsertId();
        }
        $db->prepare("INSERT OR IGNORE INTO directory_contact_roles(contact_id,role) VALUES(:id,'adoptant')")->execute([
            ':id' => $contactId,
        ]);
        $data['adopter_contact_id'] = $contactId;

        try {
            AdoptionService::adopt($data);
            header('Location: /animal?id=' . $animalId);
            exit();
        } catch (Throwable $e) {
            error_log('Échec adoption animal #' . $animalId . ' : ' . $e->getMessage());
            http_response_code(500);
            echo h(t('error.adoption_failed'));
        }
    }
}
