<?php

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

$host = "localhost";
$user = "n1035555_openplate";
$pass = "Bismillah321";
$db   = "n1035555_openplate";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    echo json_encode([
        "success" => false,
        "message" => "Koneksi database gagal"
    ]);
    exit;
}

$conn->query("
CREATE TABLE IF NOT EXISTS users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  username VARCHAR(100) NOT NULL UNIQUE,
  password VARCHAR(255) NOT NULL,
  role ENUM('admin', 'masyarakat', 'sppg', 'validator', 'pemerintah') NOT NULL,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$users = [
    ["admin", "admin123", "admin"],
    ["masyarakat", "masyarakat123", "masyarakat"],
    ["sppg", "sppg123", "sppg"],
    ["validator", "validator123", "validator"],
    ["pemerintah", "pemerintah123", "pemerintah"]
];

$stmt = $conn->prepare("
INSERT INTO users (username, password, role)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE
password = VALUES(password),
role = VALUES(role)
");

foreach ($users as $u) {
    $username = $u[0];
    $password = password_hash($u[1], PASSWORD_DEFAULT);
    $role = $u[2];

    $stmt->bind_param("sss", $username, $password, $role);
    $stmt->execute();
}

echo json_encode([
    "success" => true,
    "message" => "User berhasil dibuat / diperbarui"
]);

$conn->close();