<?php

declare(strict_types=1);

function medicine_catalog_schema_ready(): bool
{
    return schema_table_exists(table('medicine_catalog'))
        && schema_column_exists(table('prescription_items'), 'medicine_catalog_id');
}

function medicine_catalog_key(string $displayName, ?string $genericName = null, ?string $strength = null): string
{
    $parts = [trim($displayName), trim((string)$genericName), trim((string)$strength)];
    $value = mb_strtolower(implode('|', $parts));
    $value = preg_replace('/\s+/u', ' ', $value) ?: $value;
    return substr(hash('sha256', $value), 0, 40);
}

function medicine_catalog_save_custom(PDO $pdo, array $item, int $userId): ?int
{
    if (!medicine_catalog_schema_ready()) return null;
    $displayName = trim((string)($item['medication_name'] ?? ''));
    if ($displayName === '') return null;
    $genericName = trim((string)($item['generic_name'] ?? '')) ?: null;
    $strength = trim((string)($item['strength'] ?? '')) ?: null;
    $route = trim((string)($item['route'] ?? '')) ?: null;
    $key = medicine_catalog_key($displayName, $genericName, $strength);
    $stmt = $pdo->prepare(
        'INSERT INTO `' . table('medicine_catalog') . '` '
        . '(catalog_key,display_name,generic_name,strength,route,is_active,created_by,created_at,updated_at) '
        . 'VALUES (?,?,?,?,?,1,?,NOW(),NOW()) '
        . 'ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id),display_name=VALUES(display_name),generic_name=COALESCE(VALUES(generic_name),generic_name),strength=COALESCE(VALUES(strength),strength),route=COALESCE(VALUES(route),route),is_active=1,updated_at=NOW()'
    );
    $stmt->execute([$key, $displayName, $genericName, $strength, $route, $userId ?: null]);
    return (int)$pdo->lastInsertId();
}

function medicine_catalog_bind_posted_items(PDO $pdo, array $items, int $userId, bool $saveCustom = true): array
{
    $catalogIds = (array)($_POST['medicine_catalog_id'] ?? []);
    $saveFlags = (array)($_POST['save_medicine_to_catalog'] ?? []);
    foreach ($items as $index => &$item) {
        $catalogId = (int)($catalogIds[$index] ?? 0);
        if ($catalogId > 0 && medicine_catalog_schema_ready()) {
            $stmt = $pdo->prepare('SELECT id,catalog_key FROM `' . table('medicine_catalog') . '` WHERE id=? AND is_active=1 LIMIT 1');
            $stmt->execute([$catalogId]);
            $catalog = $stmt->fetch();
            $postedKey = medicine_catalog_key((string)($item['medication_name'] ?? ''), (string)($item['generic_name'] ?? ''), (string)($item['strength'] ?? ''));
            if (!$catalog || !hash_equals((string)$catalog['catalog_key'], $postedKey)) {
                $catalogId = 0;
                $saveFlags[$index] = 1;
            } else {
                $catalogId = (int)$catalog['id'];
            }
        } else {
            $catalogId = 0;
        }
        if ($saveCustom && $catalogId < 1 && !empty($saveFlags[$index])) {
            $catalogId = (int)(medicine_catalog_save_custom($pdo, $item, $userId) ?? 0);
        }
        $item['medicine_catalog_id'] = $catalogId ?: null;
    }
    unset($item);
    return $items;
}

function render_medicine_builder(array $items, bool $editable, array $fieldNames = [], string $id = 'medicine-builder'): void
{
    $names = array_merge([
        'catalog_id' => 'medicine_catalog_id[]',
        'save_catalog' => 'save_medicine_to_catalog[]',
        'medication_name' => 'medication_name[]',
        'generic_name' => 'generic_name[]',
        'indication' => 'indication[]',
        'strength' => 'strength[]',
        'dosage' => 'dosage[]',
        'frequency' => 'frequency[]',
        'route' => 'route[]',
        'duration_days' => 'duration_days[]',
        'quantity' => 'quantity[]',
        'instructions' => 'instructions[]',
    ], $fieldNames);
    $allowClinicDispense = $id === 'workspace-medicine-builder';
    $renderRow = static function(array $item, bool $editable, array $names, bool $allowClinicDispense): void {
        $catalogId = (int)($item['medicine_catalog_id'] ?? 0);
        ?>
        <article class="medicine-entry" data-medicine-row>
            <div class="medicine-entry-head"><div><strong data-medicine-title><?=e((string)($item['medication_name'] ?? 'New medicine'))?></strong><small data-medicine-source><?= $catalogId > 0 ? 'Known medicine catalog' : 'New medicine' ?></small></div><?php if($editable):?><div class="medicine-entry-actions"><?php if($allowClinicDispense):?><button type="button" class="btn ghost" data-medicine-request-dispense>Request clinic dispensing</button><?php endif;?><button type="button" class="btn ghost medicine-remove" data-medicine-remove>Remove</button></div><?php endif;?></div>
            <input type="hidden" name="<?=e($names['catalog_id'])?>" value="<?=$catalogId?>" data-medicine-catalog-id>
            <input type="hidden" name="<?=e($names['save_catalog'])?>" value="<?=$catalogId > 0 ? 0 : 1?>" data-medicine-save-catalog>
            <div class="form-grid medicine-entry-grid">
                <label>Medicine / brand name<input name="<?=e($names['medication_name'])?>" value="<?=e((string)($item['medication_name'] ?? ''))?>" data-medicine-name <?=$editable?'':'readonly'?> required></label>
                <label>Generic name<input name="<?=e($names['generic_name'])?>" value="<?=e((string)($item['generic_name'] ?? ''))?>" data-medicine-generic <?=$editable?'':'readonly'?>></label>
                <label class="wide">Indication<input name="<?=e($names['indication'])?>" value="<?=e((string)($item['indication'] ?? $item['medication_indication'] ?? ''))?>" placeholder="Reason this medicine is prescribed" <?=$editable?'':'readonly'?>></label>
                <label>Strength<input name="<?=e($names['strength'])?>" value="<?=e((string)($item['strength'] ?? ''))?>" placeholder="e.g. 500 mg" data-medicine-strength <?=$editable?'':'readonly'?>></label>
                <label>Dosage<input name="<?=e($names['dosage'])?>" value="<?=e((string)($item['dosage'] ?? ''))?>" placeholder="e.g. 1 tablet" <?=$editable?'':'readonly'?>></label>
                <label>Frequency<input name="<?=e($names['frequency'])?>" value="<?=e((string)($item['frequency'] ?? ''))?>" placeholder="e.g. Every 8 hours" <?=$editable?'':'readonly'?>></label>
                <label>Route<input name="<?=e($names['route'])?>" value="<?=e((string)($item['route'] ?? ''))?>" placeholder="e.g. Oral" data-medicine-route <?=$editable?'':'readonly'?>></label>
                <label>Duration days<input type="number" min="1" name="<?=e($names['duration_days'])?>" value="<?=e((string)($item['duration_days'] ?? ''))?>" <?=$editable?'':'readonly'?>></label>
                <label>Quantity<input name="<?=e($names['quantity'])?>" value="<?=e((string)($item['quantity'] ?? ''))?>" <?=$editable?'':'readonly'?>></label>
                <label class="wide">Instructions<textarea name="<?=e($names['instructions'])?>" <?=$editable?'':'readonly'?>><?=e((string)($item['instructions'] ?? $item['medication_instructions'] ?? ''))?></textarea></label>
            </div>
        </article>
        <?php
    };
    ?>
    <section class="medicine-builder" id="<?=e($id)?>" data-medicine-builder data-search-url="api/medicine_search.php" data-editable="<?=$editable?'1':'0'?>">
        <?php if($editable):?>
        <div class="medicine-search-shell">
            <label class="medicine-search-label">Search or add medicine
                <div class="medicine-search-line"><input type="search" data-medicine-search autocomplete="off" placeholder="Type generic name, brand, or strength"><button type="button" class="btn primary" data-medicine-add-custom>Add new</button></div>
            </label>
            <div class="medicine-search-results" data-medicine-results hidden></div>
            <p class="muted">Choose a known medicine from the clinic database, or add a new one. New medicines are saved to the catalog when the prescription is issued.</p>
        </div>
        <?php endif;?>
        <div class="medicine-items" data-medicine-items>
            <?php foreach($items as $item) $renderRow($item, $editable, $names, $allowClinicDispense); ?>
        </div>
        <?php if($editable):?>
        <template data-medicine-template><?php $renderRow([], true, $names, $allowClinicDispense); ?></template>
        <div class="medicine-empty" data-medicine-empty <?= $items ? 'hidden' : '' ?>>No medicine added yet. Search the catalog or choose <strong>Add new</strong>.</div>
        <?php endif;?>
    </section>
    <?php
}
