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

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

switch ($action) {
    case 'create':
        $name = clean($_POST['name'] ?? '');
        $type = clean($_POST['package_type'] ?? 'private');
        $price = (float)($_POST['price'] ?? 0);
        $desc = clean($_POST['description'] ?? '');
        
        if (empty($name) || $price <= 0) {
            echo json_encode(['success' => false, 'message' => 'يرجى إدخال الاسم والسعر']);
            exit;
        }
        
        $db->prepare("INSERT INTO packages (name, package_type, price, description) VALUES (?,?,?,?)")
           ->execute([$name, $type, $price, $desc]);
        echo json_encode(['success' => true, 'message' => 'تم إضافة الحزمة بنجاح']);
        break;
    
    case 'update':
        $id = (int)($_POST['id'] ?? 0);
        $db->prepare("UPDATE packages SET name=?, package_type=?, price=?, description=? WHERE id=?")
           ->execute([clean($_POST['name']), clean($_POST['package_type']), (float)$_POST['price'], clean($_POST['description'] ?? ''), $id]);
        echo json_encode(['success' => true, 'message' => 'تم تحديث الحزمة']);
        break;
    
    case 'toggle':
        $id = (int)($_POST['id'] ?? 0);
        $isActive = (int)($_POST['is_active'] ?? 0);
        $db->prepare("UPDATE packages SET is_active=? WHERE id=?")->execute([$isActive, $id]);
        echo json_encode(['success' => true, 'message' => $isActive ? 'تم تفعيل الحزمة' : 'تم تعطيل الحزمة']);
        break;
    
    case 'list':
        $type = clean($_GET['type'] ?? '');
        $sql = "SELECT * FROM packages WHERE is_active = 1";
        if ($type) $sql .= " AND package_type = '$type'";
        $sql .= " ORDER BY name";
        $list = $db->query($sql)->fetchAll();
        echo json_encode(['success' => true, 'data' => $list]);
        break;
    
    default:
        echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
}
