<?php
declare(strict_types=1);

try {
    $pdo = new PDO('mysql:host=db;dbname=db;charset=utf8mb4', 'db', 'db');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $base = '/var/www/html/data';

    $pdo->exec('SET FOREIGN_KEY_CHECKS = 0');
    $pdo->exec('SET NAMES utf8mb4');

    // ── Clear dependent pivot tables ──────────────────────────────────────────
    foreach (['doctor_provinces', 'doctor_cities', 'doctor_specialties', 'doctor_expertise', 'clinic_specialties', 'clinic_services', 'clinic_insurances'] as $t) {
        $pdo->exec("TRUNCATE TABLE `$t`");
        echo "Truncated $t\n";
    }

    // Clear location FKs on clinics
    $pdo->exec('UPDATE clinics SET province_id = NULL, city_id = NULL');

    // ── Clear main tables ─────────────────────────────────────────────────────
    foreach (['doctor_services', 'specialties', 'cities', 'provinces'] as $t) {
        $pdo->exec("DELETE FROM `$t`");
        echo "Cleared $t\n";
    }

    // ── 1. Provinces ──────────────────────────────────────────────────────────
    $states = json_decode(file_get_contents("$base/state.json"), true);
    $stmt = $pdo->prepare(
        'INSERT INTO provinces (id, uuid, name, status, weight) VALUES (?, UUID(), ?, 1, ?)'
    );
    foreach ($states as $i => $s) {
        $stmt->execute([(int)$s['id'], $s['name'], ($i + 1) * 10]);
    }
    echo 'Inserted ' . count($states) . " provinces\n";

    // ── 2. Cities ─────────────────────────────────────────────────────────────
    $cities = json_decode(file_get_contents("$base/city.json"), true);
    $stmt = $pdo->prepare(
        'INSERT INTO cities (id, uuid, name, status, weight, province_id, email, slogan, domain,
                             description, keywords, contact_phone, social_media, footer_description)
         VALUES (?, UUID(), ?, 1, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    );
    foreach ($cities as $c) {
        $social = isset($c['socialMedia']) ? json_encode($c['socialMedia'], JSON_UNESCAPED_UNICODE) : null;
        $stmt->execute([
            (int)$c['id'],
            $c['name'],
            isset($c['province_id']) ? (int)$c['province_id'] : null,
            $c['email'] ?? null,
            $c['slogan'] ?? null,
            $c['domain'] ?? null,
            $c['description'] ?? null,
            $c['keywords'] ?? null,
            $c['contactPhone'] ?? null,
            $social,
            $c['footerDescription'] ?? null,
        ]);
    }
    echo 'Inserted ' . count($cities) . " cities\n";

    // ── 3. Specialties (parents first, then children) ─────────────────────────
    $specialties = json_decode(file_get_contents("$base/specialties.json"), true);
    $parents  = array_values(array_filter($specialties, fn($s) => $s['parent'] === null));
    $children = array_values(array_filter($specialties, fn($s) => $s['parent'] !== null));

    $stmt = $pdo->prepare(
        'INSERT INTO specialties (id, uuid, name, slug, status, weight, parent_id)
         VALUES (?, UUID(), ?, ?, 1, ?, ?)'
    );
    foreach ($parents as $i => $s) {
        $stmt->execute([(int)$s['id'], $s['name'], $s['slug'], ($i + 1) * 10, null]);
    }
    foreach ($children as $i => $s) {
        $stmt->execute([(int)$s['id'], $s['name'], $s['slug'], ($i + 1) * 10, (int)$s['parent']]);
    }
    echo 'Inserted ' . count($specialties) . " specialties (" . count($parents) . " root + " . count($children) . " children)\n";

    // ── 4. Doctor services ────────────────────────────────────────────────────
    $services = json_decode(file_get_contents("$base/doctor_services.json"), true);
    $stmt = $pdo->prepare(
        'INSERT INTO doctor_services (id, uuid, name, slug, status, weight, specialty_id)
         VALUES (?, UUID(), ?, ?, 1, ?, ?)'
    );
    foreach ($services as $i => $s) {
        $stmt->execute([
            (int)$s['id'],
            $s['name'],
            $s['slug'],
            ($i + 1) * 10,
            isset($s['specialty_id']) ? (int)$s['specialty_id'] : null,
        ]);
    }
    echo 'Inserted ' . count($services) . " doctor_services\n";

    // ── Fix AUTO_INCREMENT ────────────────────────────────────────────────────
    $pdo->exec('ALTER TABLE provinces AUTO_INCREMENT = 200');
    $pdo->exec('ALTER TABLE cities AUTO_INCREMENT = 2000');
    $pdo->exec('ALTER TABLE specialties AUTO_INCREMENT = 500');
    $pdo->exec('ALTER TABLE doctor_services AUTO_INCREMENT = 30000');

    $pdo->exec('SET FOREIGN_KEY_CHECKS = 1');

    echo "\nDone! Summary:\n";
    foreach (['provinces', 'cities', 'specialties', 'doctor_services'] as $t) {
        $cnt = $pdo->query("SELECT COUNT(*) FROM `$t`")->fetchColumn();
        echo "  $t: $cnt rows\n";
    }

} catch (Throwable $e) {
    echo 'ERROR: ' . $e->getMessage() . "\n";
    exit(1);
}
