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

// Check if user is admin
if (!isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => 'Akses ditolak']);
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if ($action === 'list') {
        // Get all users (except admin accounts for security)
        $stmt = $conn->prepare("SELECT id, username, full_name, role, specialization, supervisor_initial, semester, email, phone, is_active, created_at FROM users ORDER BY role, created_at DESC");
        $stmt->execute();
        $result = $stmt->get_result();
        
        $users = [];
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
        
        echo json_encode(['success' => true, 'data' => $users]);
        $stmt->close();
    }
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        // Create new user
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $full_name = sanitize($_POST['full_name'] ?? '');
        $role = sanitize($_POST['role'] ?? 'trainee');
        $specialization = sanitize($_POST['specialization'] ?? '');
        $supervisor_initial = sanitize($_POST['supervisor_initial'] ?? '');
        $semester = ($role === 'trainee') ? intval($_POST['semester'] ?? 0) : null;
        $institution = sanitize($_POST['institution'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        
        // Validate input
        if (empty($username) || empty($password) || empty($full_name)) {
            echo json_encode(['success' => false, 'message' => 'Username, password, dan nama lengkap harus diisi']);
            exit();
        }
        
        // Validate role
        if (!in_array($role, ['trainee', 'dosen', 'admin'])) {
            echo json_encode(['success' => false, 'message' => 'Role tidak valid']);
            exit();
        }
        
        // Validate supervisor_initial for dosen
        if ($role === 'dosen' && empty($supervisor_initial)) {
            echo json_encode(['success' => false, 'message' => 'Inisial Supervisor harus diisi untuk dosen']);
            exit();
        }
        
        // Validate supervisor_initial length
        if (!empty($supervisor_initial) && strlen($supervisor_initial) !== 2) {
            echo json_encode(['success' => false, 'message' => 'Inisial Supervisor harus 2 huruf']);
            exit();
        }
        
        // Check if username already exists
        $check_stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
        $check_stmt->bind_param("s", $username);
        $check_stmt->execute();
        if ($check_stmt->get_result()->num_rows > 0) {
            echo json_encode(['success' => false, 'message' => 'Username sudah digunakan']);
            exit();
        }
        $check_stmt->close();
        
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);
        
        // Insert new user
        $stmt = $conn->prepare("INSERT INTO users (username, password, full_name, role, specialization, supervisor_initial, semester, institution, email, phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssisss", $username, $hashed_password, $full_name, $role, $specialization, $supervisor_initial, $semester, $institution, $email, $phone);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'User berhasil didaftarkan']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal mendaftarkan user: ' . $stmt->error]);
        }
        
        $stmt->close();
    } elseif ($action === 'update') {
        // Update user
        $user_id = intval($_POST['user_id'] ?? 0);
        $full_name = sanitize($_POST['full_name'] ?? '');
        $role = sanitize($_POST['role'] ?? 'trainee');
        $specialization = sanitize($_POST['specialization'] ?? '');
        $supervisor_initial = sanitize($_POST['supervisor_initial'] ?? '');
        $semester = ($_POST['semester'] !== '' && $_POST['semester'] !== null) ? intval($_POST['semester']) : null;
        $institution = sanitize($_POST['institution'] ?? '');
        $email = sanitize($_POST['email'] ?? '');
        $phone = sanitize($_POST['phone'] ?? '');
        
        if (empty($user_id)) {
            echo json_encode(['success' => false, 'message' => 'User ID harus diisi']);
            exit();
        }
        
        // Validate role
        if (!in_array($role, ['trainee', 'dosen', 'admin'])) {
            echo json_encode(['success' => false, 'message' => 'Role tidak valid']);
            exit();
        }
        
        // Validate supervisor_initial for dosen
        if ($role === 'dosen' && empty($supervisor_initial)) {
            echo json_encode(['success' => false, 'message' => 'Inisial Supervisor harus diisi untuk dosen']);
            exit();
        }
        
        // Validate supervisor_initial length
        if (!empty($supervisor_initial) && strlen($supervisor_initial) !== 2) {
            echo json_encode(['success' => false, 'message' => 'Inisial Supervisor harus 2 huruf']);
            exit();
        }
        
        // Handle password update if provided
        $password = $_POST['password'] ?? '';
        
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_BCRYPT);
            $stmt = $conn->prepare("UPDATE users SET full_name = ?, role = ?, specialization = ?, supervisor_initial = ?, semester = ?, institution = ?, email = ?, phone = ?, password = ? WHERE id = ?");
            $stmt->bind_param("ssssissssi", $full_name, $role, $specialization, $supervisor_initial, $semester, $institution, $email, $phone, $hashed_password, $user_id);
        } else {
            $stmt = $conn->prepare("UPDATE users SET full_name = ?, role = ?, specialization = ?, supervisor_initial = ?, semester = ?, institution = ?, email = ?, phone = ? WHERE id = ?");
            $stmt->bind_param("sssssissi", $full_name, $role, $specialization, $supervisor_initial, $semester, $institution, $email, $phone, $user_id);
        }
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'User berhasil diperbarui']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal memperbarui user: ' . $stmt->error]);
        }
        
        $stmt->close();
    } elseif ($action === 'toggle_status') {
        // Toggle user active status
        $user_id = intval($_POST['user_id'] ?? 0);
        
        if (empty($user_id)) {
            echo json_encode(['success' => false, 'message' => 'User ID harus diisi']);
            exit();
        }
        
        // Get current status
        $check_stmt = $conn->prepare("SELECT is_active FROM users WHERE id = ?");
        $check_stmt->bind_param("i", $user_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'User tidak ditemukan']);
            exit();
        }
        
        $user = $result->fetch_assoc();
        $new_status = $user['is_active'] ? 0 : 1;
        $check_stmt->close();
        
        $stmt = $conn->prepare("UPDATE users SET is_active = ? WHERE id = ?");
        $stmt->bind_param("ii", $new_status, $user_id);
        
        if ($stmt->execute()) {
            $status_text = $new_status ? 'diaktifkan' : 'dinonaktifkan';
            echo json_encode(['success' => true, 'message' => 'User berhasil ' . $status_text]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal mengubah status user']);
        }
        
        $stmt->close();
    } elseif ($action === 'delete') {
        // Delete user
        $user_id = intval($_POST['user_id'] ?? 0);
        
        if (empty($user_id)) {
            echo json_encode(['success' => false, 'message' => 'User ID harus diisi']);
            exit();
        }
        
        $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'User berhasil dihapus']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Gagal menghapus user']);
        }
        
        $stmt->close();
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
