<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

include 'koneksi.php';

$action = $_POST['action'] ?? '';

try {
    if ($action === 'approve_petugas') {
        $id = (int)$_POST['id'];
        $stmt = $pdo->prepare("UPDATE users SET status = 'active' WHERE id = ? AND role = 'petugas'");
        $stmt->execute([$id]);
        echo json_encode(['status' => 'success']);
    } 
    elseif ($action === 'reject_petugas') {
        $id = (int)$_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ? AND role = 'petugas' AND status = 'pending'");
        $stmt->execute([$id]);
        echo json_encode(['status' => 'success']);
    }
    elseif ($action === 'toggle_setting') {
        $key = $_POST['key'];
        $val = $_POST['value'];
        $stmt = $pdo->prepare("UPDATE settings SET setting_value = ? WHERE setting_key = ?");
        $stmt->execute([$val, $key]);
        echo json_encode(['status' => 'success']);
    }
    elseif ($action === 'update_user') {
        $id = (int)$_POST['id'];
        $role = $_POST['role'];
        $status = $_POST['status'];
        
        // Cek jika ini adalah admin utama
        $stmt = $pdo->prepare("SELECT username FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $userTarget = $stmt->fetch();
        if ($userTarget && $userTarget['username'] === 'admin') {
            echo json_encode(['status' => 'error', 'message' => 'Akun Admin Utama tidak dapat diubah hak akses atau statusnya.']);
            exit;
        }
        
        // Cek admin terakhir
        if ($role !== 'admin' || $status !== 'active') {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id != ?");
            $stmt->execute([$id]);
            if ($stmt->fetchColumn() == 0) {
                echo json_encode(['status' => 'error', 'message' => 'Harus ada minimal satu admin aktif']);
                exit;
            }
        }
        
        $stmt = $pdo->prepare("UPDATE users SET role = ?, status = ? WHERE id = ?");
        $stmt->execute([$role, $status, $id]);
        echo json_encode(['status' => 'success']);
    }
    elseif ($action === 'delete_user') {
        $id = (int)$_POST['id'];
        
        $stmt = $pdo->prepare("SELECT username, role, status FROM users WHERE id = ?");
        $stmt->execute([$id]);
        $user = $stmt->fetch();
        
        if (!$user) {
            echo json_encode(['status' => 'error', 'message' => 'User tidak ditemukan']);
            exit;
        }
        
        if ($user['username'] === 'admin') {
            echo json_encode(['status' => 'error', 'message' => 'Akun Admin Utama tidak dapat dihapus.']);
            exit;
        }
        
        // Cek admin terakhir
        if ($user['role'] === 'admin' && $user['status'] === 'active') {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE role = 'admin' AND status = 'active' AND id != ?");
            $stmt->execute([$id]);
            if ($stmt->fetchColumn() == 0) {
                echo json_encode(['status' => 'error', 'message' => 'Tidak dapat menghapus admin aktif terakhir']);
                exit;
            }
        }
        
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$id]);
        echo json_encode(['status' => 'success']);
    }
    else {
        echo json_encode(['status' => 'error', 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
