<?php

declare(strict_types=1);

final class DewormingController
{
    public static function save(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            http_response_code(405);
            return;
        }
        if (!PermissionService::can('medical')) {
            http_response_code(403);
            echo h(t('error.access_denied'));
            return;
        }
        $db = DB::pdo();
        $animalId = (int) ($_POST['animal_id'] ?? 0);
        $date = trim((string) ($_POST['administered_on'] ?? ''));
        $dewormer = (int) ($_POST['dewormer_id'] ?? 0);
        if (!$animalId || !self::date($date)) {
            http_response_code(400);
            echo h(t('deworm.invalid_date'));
            return;
        }
        $s = $db->prepare('SELECT 1 FROM animals WHERE id=? AND deleted_at IS NULL');
        $s->execute([$animalId]);
        if (!$s->fetchColumn()) {
            http_response_code(404);
            echo h(t('error.animal_not_found'));
            return;
        }
        if (isset($_POST['create_dewormer'])) {
            $name = trim((string) ($_POST['new_dewormer_name'] ?? ''));
            if ($name === '') {
                http_response_code(400);
                echo h(t('deworm.name_required'));
                return;
            }
            $s = $db->prepare('SELECT id FROM ref_dewormers WHERE name=? COLLATE NOCASE');
            $s->execute([$name]);
            $dewormer = (int) $s->fetchColumn();
            if (!$dewormer) {
                $db->prepare('INSERT INTO ref_dewormers(name,active_ingredient,form) VALUES(?,?,?)')->execute([
                    mb_substr($name, 0, 150),
                    trim((string) ($_POST['new_dewormer_ingredient'] ?? '')) ?: null,
                    trim((string) ($_POST['new_dewormer_form'] ?? '')) ?: null,
                ]);
                $dewormer = (int) $db->lastInsertId();
            }
        }
        if ($dewormer) {
            $s = $db->prepare('SELECT 1 FROM ref_dewormers WHERE id=? AND active=1');
            $s->execute([$dewormer]);
            if (!$s->fetchColumn()) {
                $dewormer = 0;
            }
        }
        $ids = [$animalId];
        $litterId = null;
        if (isset($_POST['apply_litter'])) {
            $s = $db->prepare(
                'SELECT l.id FROM litters l LEFT JOIN litter_kittens lk ON lk.litter_id=l.id WHERE l.mother_id=? OR lk.animal_id=? ORDER BY l.id DESC LIMIT 1',
            );
            $s->execute([$animalId, $animalId]);
            $litterId = (int) $s->fetchColumn() ?: null;
            if ($litterId) {
                $s = $db->prepare(
                    'SELECT animal_id FROM litter_kittens WHERE litter_id=? UNION SELECT mother_id FROM litters WHERE id=? AND mother_id IS NOT NULL',
                );
                $s->execute([$litterId, $litterId]);
                $ids = array_values(array_unique(array_map('intval', $s->fetchAll(PDO::FETCH_COLUMN))));
            }
        }
        $manual = trim((string) ($_POST['next_due_date'] ?? ''));
        if ($manual !== '' && !self::date($manual)) {
            http_response_code(400);
            echo h(t('deworm.invalid_next_due'));
            return;
        }
        $db->beginTransaction();
        try {
            $insert = $db->prepare(
                'INSERT INTO dewormings(animal_id,dewormer_id,administered_on,dose_text,weight_kg,next_due_date,notes,source_litter_id,created_by) VALUES(?,?,?,?,?,?,?,?,?)',
            );
            $history = $db->prepare(
                "INSERT INTO animal_history(animal_id,type,label,details,user_id) VALUES(?,'deworming','Vermifuge administré',?,?)",
            );
            foreach ($ids as $id) {
                $s = $db->prepare('SELECT name,birth_date FROM animals WHERE id=? AND deleted_at IS NULL');
                $s->execute([$id]);
                $animal = $s->fetch();
                if (!$animal) {
                    continue;
                }
                $next = $manual ?: self::nextDue($animal['birth_date'] ?? null, $date);
                $insert->execute([
                    $id,
                    $dewormer ?: null,
                    $date,
                    trim((string) ($_POST['dose_text'] ?? '')) ?: null,
                    ($_POST['weight_kg'] ?? '') !== '' ? (float) $_POST['weight_kg'] : null,
                    $next,
                    trim((string) ($_POST['notes'] ?? '')) ?: null,
                    $litterId,
                    Auth::id(),
                ]);
                $history->execute([
                    $id,
                    'Administration : ' . self::fr($date) . ($next ? ' · Prochaine échéance : ' . self::fr($next) : ''),
                    Auth::id(),
                ]);
            }
            $perAnimal = (float) str_replace(',', '.', (string) ($_POST['inventory_quantity'] ?? 0));
            InventoryService::consumeBatch(
                (int) ($_POST['inventory_batch_id'] ?? 0),
                $perAnimal * count($ids),
                $animalId,
                'Vermifuge du ' . $date . ($litterId ? ' · portée #' . $litterId : ''),
            );
            $db->commit();
            header('Location: /animal?id=' . $animalId . '#tab-med');
            exit();
        } catch (Throwable $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            throw $e;
        }
    }
    public static function nextDue(?string $birth, string $given): string
    {
        $admin = new DateTimeImmutable($given);
        if ($birth && ($born = DateTimeImmutable::createFromFormat('!Y-m-d', $birth))) {
            $targets = [
                $born->modify('+3 weeks'),
                $born->modify('+5 weeks'),
                $born->modify('+7 weeks'),
                $born->modify('+3 months'),
                $born->modify('+4 months'),
                $born->modify('+5 months'),
                $born->modify('+6 months'),
            ];
            foreach ($targets as $target) {
                if ($target > $admin) {
                    return $target->format('Y-m-d');
                }
            }
        }
        return $admin->modify('+3 months')->format('Y-m-d');
    }
    private static function date(string $v): bool
    {
        $d = DateTimeImmutable::createFromFormat('!Y-m-d', $v);
        return $d && $d->format('Y-m-d') === $v;
    }
    private static function fr(string $v): string
    {
        $d = DateTimeImmutable::createFromFormat('!Y-m-d', $v);
        return $d ? $d->format('d/m/Y') : $v;
    }
}
