<?php
// ============================================================
// koneksi.php — Database Connection (PDO)
// ============================================================

define('DB_HOST', getenv('DB_HOST') ?: 'localhost');
define('DB_USER', getenv('DB_USER') ?: 'root');
define('DB_PASS', getenv('DB_PASS') !== false ? getenv('DB_PASS') : '');
define('DB_NAME', getenv('DB_NAME') ?: 'webgis');
define('DB_CHARSET', 'utf8mb4');

$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
    
    // ============================================================
    // AUTO-MIGRATION SCRIPT (Sesuai Permintaan)
    // ============================================================
    
    // 1. Buat tabel users jika belum ada (fallback)
    $pdo->exec("CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(255) NOT NULL,
        role ENUM('admin','petugas','guest') NOT NULL DEFAULT 'guest',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");

    // 2. Cek dan tambahkan kolom baru pada tabel users
    $columns = $pdo->query("SHOW COLUMNS FROM users")->fetchAll(PDO::FETCH_COLUMN);
    
    if (!in_array('email', $columns)) {
        $pdo->exec("ALTER TABLE users ADD COLUMN email VARCHAR(150) UNIQUE NULL AFTER username");
    }
    if (!in_array('nama_lengkap', $columns)) {
        $pdo->exec("ALTER TABLE users ADD COLUMN nama_lengkap VARCHAR(150) NULL AFTER email");
    }
    if (!in_array('status', $columns)) {
        // Update user lama menjadi active terlebih dahulu jika diperlukan, tapi defaultnya active
        $pdo->exec("ALTER TABLE users ADD COLUMN status ENUM('pending', 'active') NOT NULL DEFAULT 'active' AFTER role");
    }
    if (!in_array('auth_provider', $columns)) {
        $pdo->exec("ALTER TABLE users ADD COLUMN auth_provider ENUM('local', 'google') NOT NULL DEFAULT 'local' AFTER status");
    }

    // 3. Buat tabel settings
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        setting_key VARCHAR(50) PRIMARY KEY,
        setting_value VARCHAR(255) NOT NULL
    ) ENGINE=InnoDB");

    // 4. Masukkan data default settings jika belum ada
    $pdo->exec("INSERT IGNORE INTO settings (setting_key, setting_value) VALUES ('show_demo_accounts', '1')");

    // 5. Migrasi Tabel Penduduk Miskin (Tambah foto_rumah, foto_kk)
    $pm_cols = $pdo->query("SHOW COLUMNS FROM penduduk_miskin")->fetchAll(PDO::FETCH_COLUMN);
    if (!in_array('alamat', $pm_cols)) {
        $pdo->exec("ALTER TABLE penduduk_miskin ADD COLUMN alamat TEXT NULL AFTER fasilitas_publik_id");
    }
    if (!in_array('foto_rumah', $pm_cols)) {
        $pdo->exec("ALTER TABLE penduduk_miskin ADD COLUMN foto_rumah VARCHAR(255) NULL AFTER fasilitas_publik_id");
    }
    if (!in_array('foto_kk', $pm_cols)) {
        $pdo->exec("ALTER TABLE penduduk_miskin ADD COLUMN foto_kk VARCHAR(255) NULL AFTER foto_rumah");
    }
    if (!in_array('status_bantuan', $pm_cols)) {
        $pdo->exec("ALTER TABLE penduduk_miskin ADD COLUMN status_bantuan ENUM('Belum Disalurkan', 'Proses', 'Sudah Disalurkan') DEFAULT 'Belum Disalurkan'");
    }

} catch (PDOException $e) {
    http_response_code(500);
    die(json_encode([
        'status'  => 'error',
        'message' => 'Koneksi database gagal: ' . $e->getMessage()
    ]));
}

// Legacy mysqli compatibility (untuk file yang masih menggunakannya)
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($conn) {
    mysqli_set_charset($conn, DB_CHARSET);
}
?>
