<?php
// Standalone AJAX handler for SMM services
// Direct database connection to avoid any output from includes

header('Content-Type: application/json; charset=utf-8');

session_start();

// Check login
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'Not logged in']);
    exit;
}

// Read database config directly
$dbConfigFile = dirname(__DIR__) . '/config/database.php';
$dbContent = file_get_contents($dbConfigFile);

// Extract credentials using regex
preg_match("/define\s*\(\s*['\"]DB_HOST['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $dbContent, $h);
preg_match("/define\s*\(\s*['\"]DB_NAME['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $dbContent, $n);
preg_match("/define\s*\(\s*['\"]DB_USER['\"]\s*,\s*['\"]([^'\"]+)['\"]/", $dbContent, $u);
preg_match("/define\s*\(\s*['\"]DB_PASS['\"]\s*,\s*['\"]([^'\"]*?)['\"]/", $dbContent, $p);

$dbHost = $h[1] ?? 'localhost';
$dbName = $n[1] ?? '';
$dbUser = $u[1] ?? '';
$dbPass = $p[1] ?? '';

try {
    $pdo = new PDO(
        "mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4",
        $dbUser,
        $dbPass,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error']);
    exit;
}

// Get CSRF token
$csrfToken = $_SESSION['csrf_token'] ?? '';

// Get profit margin
try {
    $stmt = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'smm_profit_margin'");
    $profitMargin = floatval($stmt->fetchColumn() ?: 20);
} catch (PDOException $e) {
    $profitMargin = 20;
}

try {
    if (!isset($_POST['csrf_token']) || $csrfToken === '' || $_POST['csrf_token'] !== $csrfToken) {
        throw new Exception('Invalid CSRF token');
    }
    
    $action = $_POST['action'] ?? '';
    $allowedFields = ['custom_name', 'custom_rate', 'custom_min', 'custom_max', 'status', 'category_id'];
    
    switch ($action) {
        case 'update_field':
            $id = (int)($_POST['id'] ?? 0);
            $field = $_POST['field'] ?? '';
            $value = $_POST['value'] ?? '';
            
            if (!$id || !in_array($field, $allowedFields)) {
                throw new Exception('Invalid parameters');
            }
            
            if ($field === 'category_id') {
                $value = $value ? (int)$value : null;
            } elseif ($field === 'custom_rate') {
                $value = (float)$value;
            } elseif (in_array($field, ['custom_min', 'custom_max'])) {
                $value = (int)$value;
            } else {
                $value = trim($value);
            }
            
            $stmt = $pdo->prepare("UPDATE smm_services SET {$field} = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$value, $id]);
            echo json_encode(['success' => true]);
            break;
            
        case 'bulk_move':
            $ids = $_POST['ids'] ?? [];
            $categoryId = (int)($_POST['category_id'] ?? 0);
            
            if (empty($ids) || !$categoryId) {
                throw new Exception('Invalid selection');
            }
            
            $ids = array_map('intval', $ids);
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $multiplier = 1 + ($profitMargin / 100);
            
            $stmt = $pdo->prepare("UPDATE smm_services SET category_id = ?, custom_rate = api_rate * ?, status = 'active', updated_at = NOW() WHERE id IN ($placeholders)");
            $stmt->execute(array_merge([$categoryId, $multiplier], $ids));
            echo json_encode(['success' => true, 'count' => $stmt->rowCount()]);
            break;
            
        case 'bulk_status':
            $ids = $_POST['ids'] ?? [];
            $status = ($_POST['status'] ?? '') === 'active' ? 'active' : 'inactive';
            
            if (empty($ids)) {
                throw new Exception('No services selected');
            }
            
            $ids = array_map('intval', $ids);
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            
            $stmt = $pdo->prepare("UPDATE smm_services SET status = ? WHERE id IN ($placeholders)");
            $stmt->execute(array_merge([$status], $ids));
            echo json_encode(['success' => true, 'count' => $stmt->rowCount()]);
            break;
            
        case 'apply_margin':
            $ids = $_POST['ids'] ?? [];
            
            if (empty($ids)) {
                throw new Exception('No services selected');
            }
            
            $ids = array_map('intval', $ids);
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $multiplier = 1 + ($profitMargin / 100);
            
            $stmt = $pdo->prepare("UPDATE smm_services SET custom_rate = api_rate * ? WHERE id IN ($placeholders)");
            $stmt->execute(array_merge([$multiplier], $ids));
            echo json_encode(['success' => true, 'count' => $stmt->rowCount()]);
            break;
            
        case 'create_category':
            $name = trim($_POST['name'] ?? '');
            if (empty($name)) {
                throw new Exception('Name required');
            }
            
            $check = $pdo->prepare("SELECT id FROM smm_categories WHERE name = ?");
            $check->execute([$name]);
            if ($check->fetch()) {
                throw new Exception('Category exists');
            }
            
            $stmt = $pdo->prepare("INSERT INTO smm_categories (name, sort_order, status, created_at) VALUES (?, 0, 'active', NOW())");
            $stmt->execute([$name]);
            echo json_encode(['success' => true, 'id' => $pdo->lastInsertId(), 'name' => $name]);
            break;
            
        case 'delete_category':
            $id = (int)($_POST['id'] ?? 0);
            if (!$id) {
                throw new Exception('Invalid ID');
            }
            
            $pdo->beginTransaction();
            $pdo->prepare("UPDATE smm_services SET category_id = NULL, status = 'inactive' WHERE category_id = ?")->execute([$id]);
            $pdo->prepare("DELETE FROM smm_categories WHERE id = ?")->execute([$id]);
            $pdo->commit();
            echo json_encode(['success' => true]);
            break;
            
        default:
            throw new Exception('Unknown action');
    }
    
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}