<?php
/**
 * Prince VIP System - Agents AJAX Handler
 */
require_once __DIR__ . '/../config/database.php';
if (!isLoggedIn() || !isAdmin()) { echo json_encode(['success' => false, 'message' => 'غير مصرح']); exit; }

$db = getDB();
$action = $_POST['action'] ?? '';

switch ($action) {
    case 'create':
        $username = clean($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $fullName = clean($_POST['full_name'] ?? '');
        
        if (empty($username) || empty($password) || empty($fullName)) {
            echo json_encode(['success' => false, 'message' => 'يرجى إكمال البيانات المطلوبة']);
            exit;
        }
        
        $check = $db->prepare("SELECT id FROM users WHERE username = ?");
        $check->execute([$username]);
        if ($check->fetch()) {
            echo json_encode(['success' => false, 'message' => 'اسم المستخدم مسجل مسبقاً']);
            exit;
        }
        
        $hashedPass = password_hash($password, PASSWORD_DEFAULT);
        $db->prepare("INSERT INTO users (username, password, full_name, email, phone, role) VALUES (?,?,?,?,?,'agent')")
           ->execute([$username, $hashedPass, $fullName, clean($_POST['email'] ?? ''), clean($_POST['phone'] ?? '')]);
        
        echo json_encode(['success' => true, 'message' => 'تم إضافة الوكيل بنجاح']);
        break;
    
    case 'update':
        $agentId = (int)($_POST['agent_id'] ?? 0);
        $db->prepare("UPDATE users SET full_name=?, email=?, phone=? WHERE id=? AND role='agent'")
           ->execute([clean($_POST['full_name']), clean($_POST['email'] ?? ''), clean($_POST['phone'] ?? ''), $agentId]);
        
        if (!empty($_POST['new_password'])) {
            $db->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($_POST['new_password'], PASSWORD_DEFAULT), $agentId]);
        }
        
        echo json_encode(['success' => true, 'message' => 'تم تحديث بيانات الوكيل']);
        break;
    
    case 'toggle':
        $agentId = (int)($_POST['agent_id'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 0);
        $db->prepare("UPDATE users SET is_active=? WHERE id=? AND role='agent'")->execute([$isActive, $agentId]);
        $msg = $isActive ? 'تم تفعيل الوكيل' : 'تم تعطيل الوكيل';
        echo json_encode(['success' => true, 'message' => $msg]);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
}
