<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/api_auth.php';

function respond(array $data, int $statusCode = 200): void
{
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$action = $_REQUEST['action'] ?? '';

try {
    if ($method === 'GET') {
        if ($action !== 'list') {
            respond([
                'success' => false,
                'message' => 'Invalid action',
                'method' => $method,
                'action' => $action
            ], 400);
        }

        $stmt = db()->query("
            SELECT
                id,
                generic_name,
                rxcui,
                strength,
                form,
                times_per_day,
                dispense_times_json,
                created_at,
                updated_at
            FROM medication_master
            ORDER BY generic_name ASC, strength ASC, form ASC
        ");

        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $medications = array_map(function ($row) {
            $dispenseTimes = json_decode($row['dispense_times_json'] ?? '[]', true);
            if (!is_array($dispenseTimes)) {
                $dispenseTimes = [];
            }

            return [
                'id' => (string)($row['id'] ?? ''),
                'genericName' => $row['generic_name'] ?? '',
                'rxCui' => $row['rxcui'] ?? '',
                'strength' => $row['strength'] ?? '',
                'form' => $row['form'] ?? '',
                'timesPerDay' => (int)($row['times_per_day'] ?? 1),
                'dispenseTimes' => $dispenseTimes,
                'dispense_times_json' => $row['dispense_times_json'] ?? '[]',
                'created_at' => $row['created_at'] ?? null,
                'updated_at' => $row['updated_at'] ?? null
            ];
        }, $rows);

        respond([
            'success' => true,
            'medications' => $medications
        ]);
    }

    if ($method === 'POST') {
        require_family_session();

        if ($action === 'create') {
            $genericName = trim($_POST['generic_name'] ?? '');
            $rxcui = trim($_POST['rxcui'] ?? '');
            $strength = trim($_POST['strength'] ?? '');
            $form = trim($_POST['form'] ?? '');
            $timesPerDay = (int)($_POST['times_per_day'] ?? 0);
            $dispenseTimesJson = trim($_POST['dispense_times_json'] ?? '[]');

            if ($genericName === '') {
                respond([
                    'success' => false,
                    'message' => 'generic_name is required'
                ], 400);
            }

            if ($timesPerDay < 1) {
                $timesPerDay = 1;
            }

            $decodedTimes = json_decode($dispenseTimesJson, true);
            if (!is_array($decodedTimes)) {
                respond([
                    'success' => false,
                    'message' => 'dispense_times_json must be valid JSON array'
                ], 400);
            }

            $decodedTimes = array_values(array_filter(array_map(function ($v) {
                return trim((string)$v);
            }, $decodedTimes), function ($v) {
                return $v !== '';
            }));

            $dispenseTimesJson = json_encode($decodedTimes);

            $stmt = db()->prepare("
                INSERT INTO medication_master
                    (generic_name, rxcui, strength, form, times_per_day, dispense_times_json, created_at, updated_at)
                VALUES
                    (?, ?, ?, ?, ?, ?, NOW(), NOW())
            ");

            $stmt->execute([
                $genericName,
                $rxcui,
                $strength,
                $form,
                $timesPerDay,
                $dispenseTimesJson
            ]);

            $newId = db()->lastInsertId();

            respond([
                'success' => true,
                'message' => 'Medication created',
                'medication' => [
                    'id' => (string)$newId,
                    'genericName' => $genericName,
                    'rxCui' => $rxcui,
                    'strength' => $strength,
                    'form' => $form,
                    'timesPerDay' => $timesPerDay,
                    'dispenseTimes' => $decodedTimes,
                    'dispense_times_json' => $dispenseTimesJson
                ]
            ]);
        }

        if ($action === 'update') {
            $id = trim($_POST['id'] ?? '');
            $genericName = trim($_POST['generic_name'] ?? '');
            $rxcui = trim($_POST['rxcui'] ?? '');
            $strength = trim($_POST['strength'] ?? '');
            $form = trim($_POST['form'] ?? '');
            $timesPerDay = (int)($_POST['times_per_day'] ?? 0);
            $dispenseTimesJson = trim($_POST['dispense_times_json'] ?? '[]');

            if ($id === '') {
                respond([
                    'success' => false,
                    'message' => 'id is required'
                ], 400);
            }

            if ($genericName === '') {
                respond([
                    'success' => false,
                    'message' => 'generic_name is required'
                ], 400);
            }

            if ($timesPerDay < 1) {
                $timesPerDay = 1;
            }

            $decodedTimes = json_decode($dispenseTimesJson, true);
            if (!is_array($decodedTimes)) {
                respond([
                    'success' => false,
                    'message' => 'dispense_times_json must be valid JSON array'
                ], 400);
            }

            $decodedTimes = array_values(array_filter(array_map(function ($v) {
                return trim((string)$v);
            }, $decodedTimes), function ($v) {
                return $v !== '';
            }));

            $dispenseTimesJson = json_encode($decodedTimes);

            $stmt = db()->prepare("
                UPDATE medication_master
                SET
                    generic_name = ?,
                    rxcui = ?,
                    strength = ?,
                    form = ?,
                    times_per_day = ?,
                    dispense_times_json = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $stmt->execute([
                $genericName,
                $rxcui,
                $strength,
                $form,
                $timesPerDay,
                $dispenseTimesJson,
                $id
            ]);

            respond([
                'success' => true,
                'message' => 'Medication updated',
                'medication' => [
                    'id' => (string)$id,
                    'genericName' => $genericName,
                    'rxCui' => $rxcui,
                    'strength' => $strength,
                    'form' => $form,
                    'timesPerDay' => $timesPerDay,
                    'dispenseTimes' => $decodedTimes,
                    'dispense_times_json' => $dispenseTimesJson
                ]
            ]);
        }

        if ($action === 'delete') {
            $id = trim($_POST['id'] ?? '');

            if ($id === '') {
                respond([
                    'success' => false,
                    'message' => 'id is required'
                ], 400);
            }

            $stmt = db()->prepare("DELETE FROM medication_master WHERE id = ?");
            $stmt->execute([$id]);

            respond([
                'success' => true,
                'message' => 'Medication deleted'
            ]);
        }

        respond([
            'success' => false,
            'message' => 'Invalid action',
            'method' => $method,
            'action' => $action
        ], 400);
    }

    respond([
        'success' => false,
        'message' => 'Method not allowed',
        'method' => $method,
        'action' => $action
    ], 405);

} catch (PDOException $e) {
    respond([
        'success' => false,
        'message' => 'Database error',
        'error' => $e->getMessage(),
        'method' => $method,
        'action' => $action
    ], 500);
} catch (Throwable $e) {
    respond([
        'success' => false,
        'message' => 'Server error',
        'error' => $e->getMessage(),
        'method' => $method,
        'action' => $action
    ], 500);
}