<?php
declare(strict_types=1);

require_once __DIR__ . '/auth.php';
require_admin_login(true);

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

$host = getenv('DB_HOST') ?: '127.0.0.1';
$username = getenv('DB_SETUP_USERNAME') ?: getenv('DB_USERNAME') ?: 'root';
$password = getenv('DB_SETUP_PASSWORD') ?: getenv('DB_PASSWORD') ?: '';
$charset = getenv('DB_CHARSET') ?: 'utf8mb4';
$schemaPath = __DIR__ . '/../sql/miskin_schema.sql';

$sql = file_get_contents($schemaPath);

if ($sql === false) {
    echo json_encode([
        'success' => false,
        'message' => 'File skema database tidak ditemukan.',
    ]);
    exit;
}

try {
    $dsn = "mysql:host={$host};charset={$charset}";
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES => false,
    ]);

    $pdo->exec($sql);

    echo json_encode([
        'success' => true,
        'message' => 'Database webgis_miskin berhasil di-reset.',
    ]);
} catch (PDOException $exception) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Gagal reset database.',
        'error' => $exception->getMessage(),
    ]);
}
