<?php

declare(strict_types=1);
final class SurgeriesController
{
    public static function form(): void
    {
        $id = (int) ($_GET['animal_id'] ?? 0);
        $db = DB::pdo();
        $s = $db->prepare('SELECT id,name,species FROM animals WHERE id=? AND deleted_at IS NULL');
        $s->execute([$id]);
        $animal = $s->fetch(PDO::FETCH_ASSOC);
        if (!$animal) {
            http_response_code(404);
            return;
        }
        $clinics = $db
            ->query(
                "SELECT DISTINCT dc.id,dc.name FROM directory_contacts dc JOIN directory_contact_roles r ON r.contact_id=dc.id WHERE dc.deleted_at IS NULL AND r.role IN ('cabinet','structure_veterinaire') ORDER BY dc.name COLLATE NOCASE",
            )
            ->fetchAll(PDO::FETCH_ASSOC);
        $vets = $db
            ->query(
                "SELECT dc.id,dc.name,dc.organization_id FROM directory_contacts dc JOIN directory_contact_roles r ON r.contact_id=dc.id AND r.role='veterinaire' WHERE dc.deleted_at IS NULL ORDER BY dc.name COLLATE NOCASE",
            )
            ->fetchAll(PDO::FETCH_ASSOC);
        $tariffs = $db
            ->query(
                "SELECT ct.id,ct.clinic_contact_id,ct.label,ct.amount_cents,COALESCE(dr.percent,0) discount FROM clinic_tariffs ct LEFT JOIN clinic_discount_rules dr ON dr.clinic_contact_id=ct.clinic_contact_id AND dr.discount_group=ct.discount_group WHERE ct.active=1 AND ct.category IN ('surgery','dental','imaging') ORDER BY ct.label COLLATE NOCASE",
            )
            ->fetchAll(PDO::FETCH_ASSOC);
        render('surgery_form.php', [
            'title' => 'Chirurgie de ' . $animal['name'],
            'animal' => $animal,
            'clinics' => $clinics,
            'vets' => $vets,
            'tariffs' => $tariffs,
        ]);
    }
    public static function save(): void
    {
        $animal = (int) ($_POST['animal_id'] ?? 0);
        $name = trim((string) ($_POST['procedure_name'] ?? ''));
        $date = (string) ($_POST['surgery_date'] ?? '');
        $category = (string) ($_POST['category'] ?? 'other');
        $status = (string) ($_POST['status'] ?? 'completed');
        if (
            !$animal ||
            $name === '' ||
            !preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) ||
            !in_array($status, ['planned', 'completed', 'cancelled'], true)
        ) {
            http_response_code(400);
            echo h(t('surgery.invalid_data'));
            return;
        }
        $db = DB::pdo();
        $tariff = (int) ($_POST['tariff_id'] ?? 0) ?: null;
        $amountRaw = str_replace(',', '.', trim((string) ($_POST['amount'] ?? '')));
        $amount = $amountRaw === '' ? null : (int) round(max(0, (float) $amountRaw) * 100);
        if ($amount === null && $tariff) {
            $q = $db->prepare(
                'SELECT amount_cents*(1-COALESCE((SELECT percent FROM clinic_discount_rules WHERE clinic_contact_id=ct.clinic_contact_id AND discount_group=ct.discount_group),0)/100.0) FROM clinic_tariffs ct WHERE id=?',
            );
            $q->execute([$tariff]);
            $v = $q->fetchColumn();
            $amount = $v === false ? null : (int) round((float) $v);
        }
        $db->beginTransaction();
        try {
            $s = $db->prepare(
                'INSERT INTO animal_surgeries(animal_id,category,procedure_name,surgery_date,status,clinic_contact_id,veterinarian_contact_id,tariff_id,amount_cents,anesthesia,notes,follow_up,created_by) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
            );
            $s->execute([
                $animal,
                $category,
                $name,
                $date,
                $status,
                (int) ($_POST['clinic_contact_id'] ?? 0) ?: null,
                (int) ($_POST['veterinarian_contact_id'] ?? 0) ?: null,
                $tariff,
                $amount,
                trim((string) ($_POST['anesthesia'] ?? '')) ?: null,
                trim((string) ($_POST['notes'] ?? '')) ?: null,
                trim((string) ($_POST['follow_up'] ?? '')) ?: null,
                Auth::id(),
            ]);
            $id = (int) $db->lastInsertId();
            if ($status === 'completed' && $amount !== null) {
                $db->prepare(
                    'INSERT INTO animal_expenses(animal_id,clinic_contact_id,tariff_id,source_type,source_id,label,occurred_on,quantity,catalog_unit_cents,discount_percent,total_cents,notes,created_by) VALUES(?,?,?,\'surgery\',?,?,?,1,?,0,?,?,?)',
                )->execute([
                    $animal,
                    (int) ($_POST['clinic_contact_id'] ?? 0) ?: null,
                    $tariff,
                    $id,
                    $name,
                    $date,
                    $amount,
                    $amount,
                    trim((string) ($_POST['notes'] ?? '')) ?: null,
                    Auth::id(),
                ]);
            }
            $db->prepare(
                "INSERT INTO animal_history(animal_id,type,label,details,user_id) VALUES(?,'medical','Chirurgie enregistrée',?,?)",
            )->execute([$animal, $name . ' — ' . $date, Auth::id()]);
            $db->commit();
            header('Location: /animal?id=' . $animal . '#tab-med');
        } catch (Throwable $e) {
            $db->rollBack();
            throw $e;
        }
    }
}
