<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once __DIR__ . '/config/db.php';

try {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // 1. Update ENUM types (DDL starts its own transaction and commits automatically)
    $pdo->exec("ALTER TABLE diagnosa MODIFY COLUMN tipe ENUM('PT', 'AD', 'FINAL') NOT NULL");
    $pdo->exec("ALTER TABLE aturan MODIFY COLUMN tipe ENUM('PT', 'AD', 'FINAL') NOT NULL");

    $pdo->beginTransaction();

    // 2. Clear then Seed Diagnoses
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    $pdo->exec("DELETE FROM kategori_cf");
    $pdo->exec("DELETE FROM aturan");
    $pdo->exec("DELETE FROM diagnosa");
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");

    $diagnosa_data = [
        ['D1', 'Gangguan Pola Tidur', 'PT'],
        ['D2', 'Dampak Aktivitas Digital', 'AD'],
        ['D3', 'Tingkat Kesehatan Mental', 'FINAL']
    ];

    $stmt = $pdo->prepare("INSERT INTO diagnosa (kode, nama, tipe) VALUES (?, ?, ?)");
    foreach ($diagnosa_data as $row) {
        $stmt->execute($row);
    }

    // 3. Seed Categories (Ringan, Sedang, Berat) for each diagnosis
    $categories = [];
    $diagnosa_ids = $pdo->query("SELECT id, tipe FROM diagnosa")->fetchAll(PDO::FETCH_KEY_PAIR);
    
    // Get IDs by Kode for precision
    $d1_id = $pdo->query("SELECT id FROM diagnosa WHERE kode = 'D1'")->fetchColumn();
    $d2_id = $pdo->query("SELECT id FROM diagnosa WHERE kode = 'D2'")->fetchColumn();
    $d3_id = $pdo->query("SELECT id FROM diagnosa WHERE kode = 'D3'")->fetchColumn();

    $cat_data = [
        // PT
        [$d1_id, 'Gangguan Pola Tidur Ringan', 0.0, 0.65],
        [$d1_id, 'Gangguan Pola Tidur Sedang', 0.66, 0.89],
        [$d1_id, 'Gangguan Pola Tidur Berat', 0.90, 1.0],
        // AD
        [$d2_id, 'Dampak Aktivitas Digital Ringan', 0.0, 0.65],
        [$d2_id, 'Dampak Aktivitas Digital Sedang', 0.66, 0.89],
        [$d2_id, 'Dampak Aktivitas Digital Berat', 0.90, 1.0],
        // FINAL
        [$d3_id, 'Tingkat Kesehatan Mental Ringan', 0.0, 0.65],
        [$d3_id, 'Tingkat Kesehatan Mental Sedang', 0.66, 0.89],
        [$d3_id, 'Tingkat Kesehatan Mental Berat', 0.90, 1.0]
    ];

    $stmt_cat = $pdo->prepare("INSERT INTO kategori_cf (id_diagnosa, nama, min_cf, max_cf) VALUES (?, ?, ?, ?)");
    foreach ($cat_data as $row) {
        $stmt_cat->execute($row);
    }

    // 4. Seed basic rule structure (R1 and R5)
    // Rule R1: Link all PT symptoms to D1
    $pdo->exec("INSERT INTO aturan (kode, id_diagnosa, tipe, deskripsi) VALUES ('R1', $d1_id, 'PT', 'Aturan penggabungan gejala Pola Tidur')");
    $r1_id = $pdo->lastInsertId();
    
    $gejala_pt = $pdo->query("SELECT id, cf_pakar FROM gejala WHERE tipe = 'PT'")->fetchAll();
    $stmt_detail = $pdo->prepare("INSERT INTO detail_aturan (id_aturan, id_gejala, cf_rule) VALUES (:r_id, :g_id, :cf_p)");
    foreach ($gejala_pt as $g) {
        $stmt_detail->execute(['r_id' => $r1_id, 'g_id' => $g['id'], 'cf_p' => $g['cf_pakar']]);
    }

    // Rule R5: Link all AD symptoms to D2
    $pdo->exec("INSERT INTO aturan (kode, id_diagnosa, tipe, deskripsi) VALUES ('R5', $d2_id, 'AD', 'Aturan penggabungan gejala Aktivitas Digital')");
    $r5_id = $pdo->lastInsertId();
    
    $gejala_ad = $pdo->query("SELECT id, cf_pakar FROM gejala WHERE tipe = 'AD'")->fetchAll();
    foreach ($gejala_ad as $g) {
        $stmt_detail->execute(['r_id' => $r5_id, 'g_id' => $g['id'], 'cf_p' => $g['cf_pakar']]);
    }

    $pdo->commit();
    echo "Flexible Rules Migration Success!\n";
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo "Error: " . $e->getMessage() . "\n";
}
