<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['admin_logged_in'])) {
    echo json_encode(['success' => false, 'message' => 'Admin required']);
    exit;
}

try {

    $starterMeds = [
        ['Valacyclovir', '500 mg', 'Tablet Oral'],
        ['Valacyclovir', '1 g', 'Tablet Oral'],
        ['Acetaminophen', '325 mg', 'Tablet Oral'],
        ['Acetaminophen', '500 mg', 'Tablet Oral'],
        ['Acetaminophen', '650 mg', 'Tablet Oral'],
        ['Acetaminophen', '800 mg', 'Tablet Oral'], // NEW
        ['Ibuprofen', '200 mg', 'Tablet Oral'],
        ['Ibuprofen', '400 mg', 'Tablet Oral'],
        ['Ibuprofen', '600 mg', 'Tablet Oral'],
        ['Ibuprofen', '800 mg', 'Tablet Oral'],
        ['Lisinopril', '10 mg', 'Tablet Oral'],
        ['Lisinopril', '20 mg', 'Tablet Oral'],
        ['Metformin', '500 mg', 'Tablet Oral'],
        ['Metformin', '1000 mg', 'Tablet Oral'],
        ['Amlodipine', '5 mg', 'Tablet Oral'],
        ['Amlodipine', '10 mg', 'Tablet Oral']
    ];

    $added = 0;
    $skipped = 0;

    foreach ($starterMeds as $med) {

        [$name, $strength, $form] = $med;

        // check if exists
        $stmt = $pdo->prepare("
            SELECT id FROM medication_master
            WHERE generic_name = ? AND strength = ? AND form = ?
            LIMIT 1
        ");
        $stmt->execute([$name, $strength, $form]);

        if ($stmt->fetch()) {
            $skipped++;
            continue;
        }

        // insert
        $stmt = $pdo->prepare("
            INSERT INTO medication_master
            (generic_name, rxcui, strength, form, times_per_day, dispense_times_json, created_at, updated_at)
            VALUES (?, '', ?, ?, 1, '[]', NOW(), NOW())
        ");

        $stmt->execute([$name, $strength, $form]);
        $added++;
    }

    echo json_encode([
        'success' => true,
        'message' => 'Starter medication import complete',
        'added' => $added,
        'skipped' => $skipped
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}