<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';

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

if (!isLoggedIn()) {
    jsonResponse(false, 'Unauthorized');
}

requireAdmin();

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

switch ($action) {
    case 'get_users':
        getUsers();
        break;
    
    case 'add_user':
        addUser();
        break;
    
    case 'update_user':
        updateUser();
        break;
    
    case 'delete_user':
        deleteUser();
        break;
    
    case 'change_password':
        changePassword();
        break;
    
    default:
        jsonResponse(false, 'Invalid action');
}

function getUsers() {
    try {
        $sql = "SELECT id, username, nama, role, created_at, updated_at 
                FROM users 
                ORDER BY created_at DESC";
        $result = query($sql, []);
        $users = [];
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
        
        jsonResponse(true, 'Success', $users);
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function addUser() {
    try {
        $username = clean($_POST['username'] ?? '');
        $nama = clean($_POST['nama'] ?? '');
        $role = clean($_POST['role'] ?? '');
        $password = $_POST['password'] ?? '';
        
        // Validasi
        if (empty($username) || empty($nama) || empty($role) || empty($password)) {
            jsonResponse(false, 'Semua field harus diisi');
        }
        
        if (strlen($password) < 6) {
            jsonResponse(false, 'Password minimal 6 karakter');
        }
        
        if (!in_array($role, ['admin', 'loket'])) {
            jsonResponse(false, 'Role tidak valid');
        }
        
        // Cek username sudah ada
        $checkSql = "SELECT id FROM users WHERE username = ?";
        $checkResult = query($checkSql, [$username], 's');
        if ($checkResult->num_rows > 0) {
            jsonResponse(false, 'Username sudah digunakan');
        }
        
        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert user
        $sql = "INSERT INTO users (username, password, nama, role) VALUES (?, ?, ?, ?)";
        insert($sql, [$username, $hashedPassword, $nama, $role], 'ssss');
        
        jsonResponse(true, 'User berhasil ditambahkan');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function updateUser() {
    try {
        $id = intval($_POST['id'] ?? 0);
        $nama = clean($_POST['nama'] ?? '');
        $role = clean($_POST['role'] ?? '');
        
        // Validasi
        if ($id <= 0 || empty($nama) || empty($role)) {
            jsonResponse(false, 'Data tidak lengkap');
        }
        
        if (!in_array($role, ['admin', 'loket'])) {
            jsonResponse(false, 'Role tidak valid');
        }
        
        // Cek user exists
        $checkSql = "SELECT id FROM users WHERE id = ?";
        $checkResult = query($checkSql, [$id], 'i');
        if ($checkResult->num_rows === 0) {
            jsonResponse(false, 'User tidak ditemukan');
        }
        
        // Update user (tanpa password)
        $sql = "UPDATE users SET nama = ?, role = ? WHERE id = ?";
        execute($sql, [$nama, $role, $id], 'ssi');
        
        jsonResponse(true, 'User berhasil diupdate');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function deleteUser() {
    try {
        $id = intval($_POST['id'] ?? 0);
        
        if ($id <= 0) {
            jsonResponse(false, 'ID tidak valid');
        }
        
        // Cek jika user sedang login
        if ($id == $_SESSION['user_id']) {
            jsonResponse(false, 'Tidak dapat menghapus user yang sedang login');
        }
        
        // Cek user exists
        $checkSql = "SELECT id FROM users WHERE id = ?";
        $checkResult = query($checkSql, [$id], 'i');
        if ($checkResult->num_rows === 0) {
            jsonResponse(false, 'User tidak ditemukan');
        }
        
        // Delete user
        $sql = "DELETE FROM users WHERE id = ?";
        execute($sql, [$id], 'i');
        
        jsonResponse(true, 'User berhasil dihapus');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}

function changePassword() {
    try {
        $id = intval($_POST['id'] ?? 0);
        $password = $_POST['password'] ?? '';
        
        // Validasi
        if ($id <= 0 || empty($password)) {
            jsonResponse(false, 'Data tidak lengkap');
        }
        
        if (strlen($password) < 6) {
            jsonResponse(false, 'Password minimal 6 karakter');
        }
        
        // Cek user exists
        $checkSql = "SELECT id FROM users WHERE id = ?";
        $checkResult = query($checkSql, [$id], 'i');
        if ($checkResult->num_rows === 0) {
            jsonResponse(false, 'User tidak ditemukan');
        }
        
        // Hash password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        
        // Update password
        $sql = "UPDATE users SET password = ? WHERE id = ?";
        execute($sql, [$hashedPassword, $id], 'si');
        
        jsonResponse(true, 'Password berhasil diubah');
    } catch (Exception $e) {
        jsonResponse(false, $e->getMessage());
    }
}
?>
