<?php
$host   = 'localhost';
$dbname = 'bansos_gis';
$user   = 'root';
$pass   = '';

// Legacy MySQLi connection used by older APIs
try {
    $conn = new mysqli($host, $user, $pass, $dbname);
    $conn->set_charset('utf8mb4');
    if ($conn->connect_error) {
        throw new Exception($conn->connect_error);
    }
    // Self-healing migration for manual recommendation column
    try {
        $checkCol = $conn->query("SHOW COLUMNS FROM `rumah_warga` LIKE 'is_rekomendasi_manual'");
        if ($checkCol && $checkCol->num_rows === 0) {
            $conn->query("ALTER TABLE `rumah_warga` ADD COLUMN `is_rekomendasi_manual` TINYINT(1) NOT NULL DEFAULT 0 AFTER `rekomendasi_bantuan`");
        }
        
        $checkColKat = $conn->query("SHOW COLUMNS FROM `rumah_warga` LIKE 'is_kategori_manual'");
        if ($checkColKat && $checkColKat->num_rows === 0) {
            $conn->query("ALTER TABLE `rumah_warga` ADD COLUMN `is_kategori_manual` TINYINT(1) NOT NULL DEFAULT 0 AFTER `kategori_kemiskinan`");
        }
        
        $checkColDikelola = $conn->query("SHOW COLUMNS FROM `rumah_warga` LIKE 'dikelola_oleh_ibadah_id'");
        if ($checkColDikelola && $checkColDikelola->num_rows === 0) {
            $conn->query("ALTER TABLE `rumah_warga` ADD COLUMN `dikelola_oleh_ibadah_id` INT NULL DEFAULT NULL AFTER `keterangan`");
        }
    } catch (Exception $ex) {}

    // Self-healing migration for no_telp column in users table
    try {
        $checkColUsers = $conn->query("SHOW COLUMNS FROM `users` LIKE 'no_telp'");
        if ($checkColUsers && $checkColUsers->num_rows === 0) {
            $conn->query("ALTER TABLE `users` ADD COLUMN `no_telp` VARCHAR(20) NULL DEFAULT NULL AFTER `email`");
        }
    } catch (Exception $ex) {}

    // Self-healing migration for RBAC & Kebutuhan tables
    try {
        $checkUsers = $conn->query("SHOW TABLES LIKE 'users'");
        if ($checkUsers && $checkUsers->num_rows === 0) {
            $sqlFile = dirname(__DIR__) . '/database/migrations.sql';
            if (file_exists($sqlFile)) {
                $sqlContent = file_get_contents($sqlFile);
                if ($conn->multi_query($sqlContent)) {
                    do {
                        if ($result = $conn->store_result()) {
                            $result->free();
                        }
                    } while ($conn->more_results() && $conn->next_result());
                }
            }
        }
    } catch (Exception $ex) {}
} catch (Exception $e) {
    http_response_code(500);
    die(json_encode([
        'success' => false,
        'message' => 'Koneksi database MySQLi gagal: ' . $e->getMessage() . '. Pastikan XAMPP Apache dan MySQL Anda aktif, serta database "bansos_gis" telah dibuat di phpMyAdmin.'
    ]));
}

// New PDO connection used by new APIs (redistribusi, etc.)
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    // Set to null — APIs that require PDO must check and throw themselves
    $pdo = null;
}