<?php
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, access");
header("Access-Control-Allow-Credentials: true");

require_once 'db.php';

$response = array();
$action = $_GET['action'] ?? '';

switch ($action) {
    case 'fetch':
        $sql = "SELECT id, username FROM admin_users";
        $result = $conn->query($sql);
        $admin_users = array();

        while ($row = $result->fetch_assoc()) {
            $admin_users[] = $row;
        }

        $response = $admin_users;
        break;

    case 'create':
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_BCRYPT);

        $sql = "INSERT INTO admin_users (username, password) VALUES ('$username', '$password')";

        if ($conn->query($sql) === TRUE) {
            $response['message'] = 'Admin user added successfully';
        } else {
            $response['error'] = 'Error adding admin user: ' . $conn->error;
        }
        break;

    case 'update':
        $id = $_POST['id'];
        $username = $_POST['username'];
        $password = $_POST['password'] ? password_hash($_POST['password'], PASSWORD_BCRYPT) : '';

        $sql = "UPDATE admin_users SET username = '$username'";
        if ($password) {
            $sql .= ", password = '$password'";
        }
        $sql .= " WHERE id = $id";

        if ($conn->query($sql) === TRUE) {
            $response['message'] = 'Admin user updated successfully';
        } else {
            $response['error'] = 'Error updating admin user: ' . $conn->error;
        }
        break;

    case 'delete':
        $id = $_GET['id'];
        $sql = "DELETE FROM admin_users WHERE id = $id";

        if ($conn->query($sql) === TRUE) {
            $response['message'] = 'Admin user deleted successfully';
        } else {
            $response['error'] = 'Error deleting admin user: ' . $conn->error;
        }
        break;

    default:
        $response['error'] = 'Invalid action';
        break;
}

echo json_encode($response);
$conn->close();
?>
