<?php
declare(strict_types=1);

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

function request_payload(): array
{
    $raw = file_get_contents('php://input');
    if (!$raw) {
        return $_POST ?: [];
    }

    $decoded = json_decode($raw, true);
    if (is_array($decoded)) {
        return $decoded;
    }

    parse_str($raw, $parsed);
    return is_array($parsed) ? $parsed : [];
}

function ensure_patient_med_tables(PDO $pdo): void
{
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS patient_medications (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
            family_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
            client_id BIGINT UNSIGNED NOT NULL,
            medication_master_id BIGINT UNSIGNED NOT NULL,
            custom_times_json TEXT NULL,
            notes TEXT NULL,
            created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            KEY idx_family_client (family_id, client_id),
            KEY idx_master (medication_master_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
}

try {
    $session = require_family_session();
    $familyId = (int)($session['family_id'] ?? 0);

    if ($familyId <= 0) {
        api_json([
            'success' => false,
            'message' => 'Family session required.'
        ], 403);
    }

    ensure_patient_med_tables(db());

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

    if ($method === 'GET') {
        $clientId = (int)($_GET['client_id'] ?? 0);

        if ($clientId <= 0) {
            api_json([
                'success' => false,
                'message' => 'client_id required'
            ], 400);
        }

        $sql = "
            SELECT
                pm.id,
                pm.client_id,
                pm.medication_master_id,
                pm.custom_times_json,
                pm.notes,
                mm.generic_name,
                mm.rxcui,
                mm.strength,
                mm.form,
                mm.times_per_day,
                mm.dispense_times_json
            FROM patient_medications pm
            LEFT JOIN medication_master mm ON mm.id = pm.medication_master_id
            WHERE pm.family_id = ? AND pm.client_id = ?
            ORDER BY pm.id DESC
        ";

        $stmt = db()->prepare($sql);
        $stmt->execute([$familyId, $clientId]);

        api_json([
            'success' => true,
            'medications' => $stmt->fetchAll(PDO::FETCH_ASSOC)
        ]);
    }

    $data = request_payload();
    $action = (string)($data['action'] ?? '');

    if ($action === 'add') {
        $clientId = (int)($data['client_id'] ?? 0);
        $masterId = (int)($data['medication_master_id'] ?? 0);
        $customTimes = (string)($data['custom_times_json'] ?? '');
        $notes = trim((string)($data['notes'] ?? ''));

        if ($clientId <= 0 || $masterId <= 0) {
            api_json([
                'success' => false,
                'message' => 'client_id and medication_master_id are required'
            ], 400);
        }

        $check = db()->prepare("
            SELECT id
            FROM patient_medications
            WHERE family_id = ? AND client_id = ? AND medication_master_id = ?
            LIMIT 1
        ");
        $check->execute([$familyId, $clientId, $masterId]);
        $existing = $check->fetch(PDO::FETCH_ASSOC);

        if ($existing) {
            api_json([
                'success' => true,
                'already_assigned' => true,
                'id' => (int)$existing['id']
            ]);
        }

        $stmt = db()->prepare("
            INSERT INTO patient_medications
                (family_id, client_id, medication_master_id, custom_times_json, notes, created_at, updated_at)
            VALUES
                (?, ?, ?, ?, ?, NOW(), NOW())
        ");
        $stmt->execute([$familyId, $clientId, $masterId, $customTimes, $notes]);

        api_json([
            'success' => true,
            'already_assigned' => false,
            'id' => (int)db()->lastInsertId()
        ]);
    }

    if ($action === 'delete') {
        $id = (int)($data['id'] ?? 0);

        if ($id <= 0) {
            api_json([
                'success' => false,
                'message' => 'id required'
            ], 400);
        }

        $stmt = db()->prepare("
            DELETE FROM patient_medications
            WHERE id = ? AND family_id = ?
        ");
        $stmt->execute([$id, $familyId]);

        api_json([
            'success' => true,
            'message' => 'Medication removed'
        ]);
    }

    api_json([
        'success' => false,
        'message' => 'Unsupported action'
    ], 400);

} catch (Throwable $e) {
    error_log('patient_medications.php error: ' . $e->getMessage());

    api_json([
        'success' => false,
        'message' => 'server error',
        'error' => $e->getMessage()
    ], 500);
}