<?php
/**
 * SMM Paket Satış Scripti - API Sağlayıcıları
 * @version 1.3.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// Demo modu kontrolü
function isDemoMode() {
    global $db;
    try {
        $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'demo_mode'");
        $stmt->execute();
        $value = $stmt->fetchColumn();
        return $value === '1' || $value === 1;
    } catch (PDOException $e) {
        return false;
    }
}

$demoMode = isDemoMode();

// Hassas bilgileri gizle
function maskSensitiveData($data, $visibleChars = 4) {
    if (strlen($data) <= $visibleChars * 2) {
        return str_repeat('•', strlen($data));
    }
    return substr($data, 0, $visibleChars) . str_repeat('•', strlen($data) - $visibleChars * 2) . substr($data, -$visibleChars);
}

// Para birimi sembolü
function getCurrencySymbol($currency) {
    $symbols = [
        'TRY' => '₺',
        'USD' => '$',
        'EUR' => '€',
        'GBP' => '£'
    ];
    return $symbols[$currency] ?? $currency;
}

// Fiyat formatlama
function formatRate($rate, $currency = 'TRY') {
    $symbol = getCurrencySymbol($currency);
    return number_format(floatval($rate), 4, ',', '.') . ' ' . $symbol;
}

// API Sınıfı
class SMMApi {
    private $apiUrl;
    private $apiKey;
    
    public function __construct($apiUrl, $apiKey) {
        $this->apiUrl = rtrim($apiUrl, '/');
        $this->apiKey = $apiKey;
    }
    
    private function request($action, $params = []) {
        $params['key'] = $this->apiKey;
        $params['action'] = $action;
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($params),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded']
        ]);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            return ['error' => 'Bağlantı hatası: ' . $error];
        }
        
        $data = json_decode($response, true);
        return $data ?: ['error' => 'Geçersiz API yanıtı'];
    }
    
    public function getBalance() {
        return $this->request('balance');
    }
    
    public function getServices() {
        return $this->request('services');
    }
}

// AJAX: API'den Servisleri Getir
if (isset($_GET['ajax']) && $_GET['ajax'] === 'get_services') {
    header('Content-Type: application/json');
    
    $providerId = (int)($_GET['provider_id'] ?? 0);
    
    try {
        $stmt = $db->prepare("SELECT * FROM api_providers WHERE id = ?");
        $stmt->execute([$providerId]);
        $provider = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$provider) {
            throw new Exception('Sağlayıcı bulunamadı.');
        }
        
        $api = new SMMApi($provider['api_url'], $provider['api_key']);
        $services = $api->getServices();
        
        if (isset($services['error'])) {
            throw new Exception($services['error']);
        }
        
        if (!is_array($services)) {
            throw new Exception('Servis listesi alınamadı.');
        }
        
        // Kategorilere göre grupla
        $categories = [];
        foreach ($services as $service) {
            $catName = $service['category'] ?? 'Diğer';
            if (!isset($categories[$catName])) {
                $categories[$catName] = [
                    'name' => $catName,
                    'services' => [],
                    'count' => 0
                ];
            }
            $categories[$catName]['services'][] = [
                'id' => $service['service'] ?? $service['id'] ?? 0,
                'name' => $service['name'] ?? 'Bilinmeyen',
                'type' => $service['type'] ?? 'Default',
                'rate' => floatval($service['rate'] ?? 0),
                'min' => $service['min'] ?? 1,
                'max' => $service['max'] ?? 10000,
                'category' => $catName
            ];
            $categories[$catName]['count']++;
        }
        
        ksort($categories);
        
        // Mevcut eklenen servisleri al
        $existingStmt = $db->prepare("SELECT service_id FROM api_services WHERE provider_id = ?");
        $existingStmt->execute([$providerId]);
        $existingServices = $existingStmt->fetchAll(PDO::FETCH_COLUMN);
        
        echo json_encode([
            'success' => true,
            'categories' => array_values($categories),
            'total' => count($services),
            'existing' => $existingServices,
            'currency' => $provider['currency'],
            'currency_symbol' => getCurrencySymbol($provider['currency']),
            'rate_multiplier' => $provider['rate_multiplier']
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// AJAX: Mevcut Kayıtlı Servisleri Getir
if (isset($_GET['ajax']) && $_GET['ajax'] === 'get_existing_services') {
    header('Content-Type: application/json');
    
    $providerId = (int)($_GET['provider_id'] ?? 0);
    
    try {
        // Sağlayıcı bilgisini al (para birimi için)
        $providerStmt = $db->prepare("SELECT currency FROM api_providers WHERE id = ?");
        $providerStmt->execute([$providerId]);
        $providerInfo = $providerStmt->fetch(PDO::FETCH_ASSOC);
        $currency = $providerInfo['currency'] ?? 'TRY';
        
        $stmt = $db->prepare("
            SELECT * FROM api_services 
            WHERE provider_id = ? 
            ORDER BY category ASC, name ASC
        ");
        $stmt->execute([$providerId]);
        $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Kategorilere göre grupla
        $categories = [];
        foreach ($services as $service) {
            $catName = $service['category'] ?? 'Diğer';
            if (!isset($categories[$catName])) {
                $categories[$catName] = [
                    'name' => $catName,
                    'services' => [],
                    'count' => 0
                ];
            }
            $service['rate'] = floatval($service['rate']);
            $categories[$catName]['services'][] = $service;
            $categories[$catName]['count']++;
        }
        
        ksort($categories);
        
        echo json_encode([
            'success' => true,
            'categories' => array_values($categories),
            'total' => count($services),
            'currency' => $currency,
            'currency_symbol' => getCurrencySymbol($currency)
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// AJAX: Seçilen Servisleri Kaydet
if (isset($_POST['ajax']) && $_POST['ajax'] === 'save_services') {
    header('Content-Type: application/json');
    
    if (isDemoMode()) {
        echo json_encode(['success' => false, 'error' => 'Demo modunda bu işlem yapılamaz.']);
        exit;
    }
    
    try {
        if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
            throw new Exception('Güvenlik hatası.');
        }
        
        $providerId = (int)($_POST['provider_id'] ?? 0);
        $services = json_decode($_POST['services'] ?? '[]', true);
        $mode = $_POST['mode'] ?? 'add';
        
        if (empty($services)) {
            throw new Exception('Servis seçilmedi.');
        }
        
        $stmt = $db->prepare("SELECT * FROM api_providers WHERE id = ?");
        $stmt->execute([$providerId]);
        $provider = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$provider) {
            throw new Exception('Sağlayıcı bulunamadı.');
        }
        
        if ($mode === 'replace') {
            $db->prepare("DELETE FROM api_services WHERE provider_id = ?")->execute([$providerId]);
        }
        
        $insertStmt = $db->prepare("
            INSERT INTO api_services (provider_id, service_id, name, category, type, rate, min, max, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ON DUPLICATE KEY UPDATE name = VALUES(name), category = VALUES(category), 
            type = VALUES(type), rate = VALUES(rate), min = VALUES(min), max = VALUES(max)
        ");
        
        $count = 0;
        foreach ($services as $service) {
            $insertStmt->execute([
                $providerId,
                $service['id'],
                $service['name'],
                $service['category'],
                $service['type'],
                floatval($service['rate']),
                $service['min'],
                $service['max']
            ]);
            $count++;
        }
        
        $db->prepare("UPDATE api_providers SET last_sync_at = NOW() WHERE id = ?")->execute([$providerId]);
        
        echo json_encode(['success' => true, 'count' => $count]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// AJAX: Seçilen Servisleri Sil
if (isset($_POST['ajax']) && $_POST['ajax'] === 'delete_selected_services') {
    header('Content-Type: application/json');
    
    if (isDemoMode()) {
        echo json_encode(['success' => false, 'error' => 'Demo modunda bu işlem yapılamaz.']);
        exit;
    }
    
    try {
        if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
            throw new Exception('Güvenlik hatası.');
        }
        
        $providerId = (int)($_POST['provider_id'] ?? 0);
        $serviceIds = json_decode($_POST['service_ids'] ?? '[]', true);
        
        if (empty($serviceIds)) {
            throw new Exception('Servis seçilmedi.');
        }
        
        $placeholders = implode(',', array_fill(0, count($serviceIds), '?'));
        $params = array_merge([$providerId], $serviceIds);
        
        $stmt = $db->prepare("DELETE FROM api_services WHERE provider_id = ? AND id IN ($placeholders)");
        $stmt->execute($params);
        
        $count = $stmt->rowCount();
        
        echo json_encode(['success' => true, 'count' => $count]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Normal POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['ajax'])) {
    if (isDemoMode()) {
        setFlash('error', '🔒 Demo modunda bu işlem yapılamaz.');
        redirect(SITE_URL . '/admin/api-saglayicilar.php');
        exit;
    }
    
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/api-saglayicilar.php');
        exit;
    }
    
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'add_provider':
                $name = trim($_POST['name'] ?? '');
                $apiUrl = trim($_POST['api_url'] ?? '');
                $apiKey = trim($_POST['api_key'] ?? '');
                $rateMultiplier = (float)($_POST['rate_multiplier'] ?? 1);
                $currency = $_POST['currency'] ?? 'TRY';
                
                if (empty($name) || empty($apiUrl) || empty($apiKey)) {
                    throw new Exception('Tüm alanları doldurun.');
                }
                
                $api = new SMMApi($apiUrl, $apiKey);
                $balanceResult = $api->getBalance();
                
                if (isset($balanceResult['error'])) {
                    throw new Exception('API bağlantısı başarısız: ' . $balanceResult['error']);
                }
                
                $balance = $balanceResult['balance'] ?? 0;
                
                $stmt = $db->prepare("
                    INSERT INTO api_providers (name, api_url, api_key, balance, currency, rate_multiplier, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())
                ");
                $stmt->execute([$name, $apiUrl, $apiKey, $balance, $currency, $rateMultiplier]);
                
                $symbol = getCurrencySymbol($currency);
                setFlash('success', 'API sağlayıcı eklendi. Bakiye: ' . number_format($balance, 2, ',', '.') . ' ' . $symbol);
                break;
                
            case 'update_provider':
                $id = (int)$_POST['provider_id'];
                $name = trim($_POST['name'] ?? '');
                $apiUrl = trim($_POST['api_url'] ?? '');
                $apiKey = trim($_POST['api_key'] ?? '');
                $rateMultiplier = (float)($_POST['rate_multiplier'] ?? 1);
                $currency = $_POST['currency'] ?? 'TRY';
                $status = $_POST['status'] ?? 'active';
                
                $stmt = $db->prepare("
                    UPDATE api_providers SET name = ?, api_url = ?, api_key = ?, 
                    currency = ?, rate_multiplier = ?, status = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([$name, $apiUrl, $apiKey, $currency, $rateMultiplier, $status, $id]);
                
                setFlash('success', 'Sağlayıcı güncellendi.');
                break;
                
            case 'delete_provider':
                $id = (int)$_POST['provider_id'];
                $db->prepare("DELETE FROM api_providers WHERE id = ?")->execute([$id]);
                $db->prepare("DELETE FROM api_services WHERE provider_id = ?")->execute([$id]);
                
                setFlash('success', 'Sağlayıcı silindi.');
                break;
                
            case 'sync_balance':
                $id = (int)$_POST['provider_id'];
                
                $stmt = $db->prepare("SELECT * FROM api_providers WHERE id = ?");
                $stmt->execute([$id]);
                $provider = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$provider) {
                    throw new Exception('Sağlayıcı bulunamadı.');
                }
                
                $api = new SMMApi($provider['api_url'], $provider['api_key']);
                $result = $api->getBalance();
                
                if (isset($result['error'])) {
                    throw new Exception($result['error']);
                }
                
                $balance = $result['balance'] ?? 0;
                $stmt = $db->prepare("UPDATE api_providers SET balance = ?, last_sync_at = NOW() WHERE id = ?");
                $stmt->execute([$balance, $id]);
                
                $symbol = getCurrencySymbol($provider['currency']);
                setFlash('success', 'Bakiye güncellendi: ' . number_format($balance, 2, ',', '.') . ' ' . $symbol);
                break;
                
            case 'delete_all_services':
                $id = (int)$_POST['provider_id'];
                $db->prepare("DELETE FROM api_services WHERE provider_id = ?")->execute([$id]);
                setFlash('success', 'Tüm servisler silindi.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/api-saglayicilar.php');
    exit;
}

// Sağlayıcıları çek
try {
    $providers = $db->query("
        SELECT p.*, 
               (SELECT COUNT(*) FROM api_services WHERE provider_id = p.id) as service_count
        FROM api_providers p 
        ORDER BY p.created_at DESC
    ")->fetchAll();
} catch (PDOException $e) {
    $providers = [];
}

$adminPageTitle = 'API Sağlayıcıları';
require_once __DIR__ . '/header.php';
?>

<style>
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 25px; flex-wrap: wrap; gap: 15px; }
.page-header h2 { font-size: 18px; margin: 0; display: flex; align-items: center; gap: 10px; }
.page-header h2 i { color: var(--primary); }

.demo-banner { background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(239, 68, 68, 0.15)); border: 1px solid rgba(245, 158, 11, 0.3); border-radius: 12px; padding: 15px 20px; margin-bottom: 20px; display: flex; align-items: center; gap: 12px; }
.demo-banner i { font-size: 24px; color: #f59e0b; }
.demo-banner-text h4 { margin: 0 0 4px; font-size: 14px; font-weight: 600; color: #f59e0b; }
.demo-banner-text p { margin: 0; font-size: 12px; color: var(--text-secondary); }

.providers-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px; }
.provider-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; overflow: hidden; transition: all 0.3s; }
.provider-card:hover { border-color: rgba(var(--primary-rgb), 0.3); box-shadow: 0 10px 30px rgba(0,0,0,0.2); }
.provider-header { padding: 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; justify-content: space-between; }
.provider-info { display: flex; align-items: center; gap: 12px; }
.provider-icon { width: 48px; height: 48px; background: var(--gradient); border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 20px; color: #fff; }
.provider-name { font-size: 16px; font-weight: 700; margin: 0 0 4px; }
.provider-url { font-size: 12px; color: var(--text-secondary); max-width: 180px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.provider-url.masked { font-family: monospace; letter-spacing: 1px; }
.provider-status { padding: 5px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.provider-status.active { background: rgba(16,185,129,0.15); color: #10b981; }
.provider-status.inactive { background: rgba(239,68,68,0.15); color: #ef4444; }
.provider-body { padding: 20px; }
.provider-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px; }
.provider-stat { text-align: center; padding: 15px 10px; background: var(--bg-hover); border-radius: 10px; }
.provider-stat-value { font-size: 18px; font-weight: 700; margin-bottom: 4px; }
.provider-stat-value.balance { color: #10b981; }
.provider-stat-label { font-size: 11px; color: var(--text-secondary); }
.provider-meta { display: flex; flex-direction: column; gap: 8px; margin-bottom: 20px; font-size: 12px; color: var(--text-secondary); }
.provider-meta-item { display: flex; align-items: center; gap: 8px; }
.provider-meta-item i { width: 16px; color: var(--primary); }
.provider-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
.provider-actions .btn { padding: 10px 8px; font-size: 11px; display: flex; align-items: center; justify-content: center; gap: 5px; border: none; border-radius: 8px; cursor: pointer; transition: all 0.2s; }
.btn-sync { background: rgba(59,130,246,0.15); color: #3b82f6; }
.btn-sync:hover { background: #3b82f6; color: #fff; }
.btn-add-services { background: rgba(16,185,129,0.15); color: #10b981; }
.btn-add-services:hover { background: #10b981; color: #fff; }
.btn-view-services { background: rgba(139,92,246,0.15); color: #8b5cf6; }
.btn-view-services:hover { background: #8b5cf6; color: #fff; }
.btn-edit { background: rgba(245,158,11,0.15); color: #f59e0b; }
.btn-edit:hover { background: #f59e0b; color: #fff; }
.btn-delete { background: rgba(239,68,68,0.15); color: #ef4444; }
.btn-delete:hover { background: #ef4444; color: #fff; }
.btn:disabled, .btn.disabled { opacity: 0.5; cursor: not-allowed; }

.empty-state { text-align: center; padding: 80px 20px; background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; }
.empty-state i { font-size: 60px; color: var(--primary); opacity: 0.3; margin-bottom: 20px; }
.empty-state h3 { font-size: 20px; margin-bottom: 10px; }
.empty-state p { color: var(--text-secondary); margin-bottom: 25px; }

.modal-content { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; color: var(--text-primary); }
.modal-header { border-bottom: 1px solid var(--border-color); padding: 20px; }
.modal-title { font-size: 18px; font-weight: 700; }
.modal-body { padding: 20px; }
.modal-footer { border-top: 1px solid var(--border-color); padding: 15px 20px; gap: 10px; }
.form-text { font-size: 12px; color: var(--text-secondary); margin-top: 5px; }
.modal-xl { max-width: 1200px; }

.services-loading { text-align: center; padding: 60px 20px; }
.services-loading i { font-size: 48px; color: var(--primary); margin-bottom: 15px; }
.services-header { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid var(--border-color); }
.services-stats { display: flex; gap: 20px; }
.services-stat { text-align: center; }
.services-stat-value { font-size: 24px; font-weight: 700; color: var(--primary); }
.services-stat-label { font-size: 11px; color: var(--text-secondary); }
.services-search { position: relative; width: 300px; }
.services-search input { width: 100%; padding: 10px 15px 10px 40px; background: var(--bg-hover); border: 1px solid var(--border-color); border-radius: 8px; color: var(--text-primary); font-size: 13px; }
.services-search i { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--text-secondary); }
.services-actions { display: flex; gap: 10px; }
.services-actions .btn { padding: 8px 16px; font-size: 12px; border-radius: 8px; border: none; cursor: pointer; display: flex; align-items: center; gap: 6px; }
.btn-select-all { background: rgba(59,130,246,0.15); color: #3b82f6; }
.btn-select-all:hover { background: #3b82f6; color: #fff; }
.btn-deselect-all { background: rgba(107,114,128,0.15); color: #6b7280; }
.btn-deselect-all:hover { background: #6b7280; color: #fff; }
.btn-delete-selected { background: rgba(239,68,68,0.15); color: #ef4444; }
.btn-delete-selected:hover { background: #ef4444; color: #fff; }

.categories-container { max-height: 500px; overflow-y: auto; padding-right: 10px; }
.category-item { background: var(--bg-hover); border: 1px solid var(--border-color); border-radius: 12px; margin-bottom: 12px; overflow: hidden; }
.category-header { display: flex; align-items: center; justify-content: space-between; padding: 15px; cursor: pointer; transition: background 0.2s; }
.category-header:hover { background: rgba(var(--primary-rgb), 0.05); }
.category-left { display: flex; align-items: center; gap: 12px; }
.category-checkbox { width: 20px; height: 20px; border: 2px solid var(--border-color); border-radius: 4px; display: flex; align-items: center; justify-content: center; cursor: pointer; transition: all 0.2s; }
.category-checkbox.checked { background: var(--primary); border-color: var(--primary); }
.category-checkbox.partial { background: rgba(var(--primary-rgb), 0.3); border-color: var(--primary); }
.category-checkbox i { color: #fff; font-size: 10px; display: none; }
.category-checkbox.checked i, .category-checkbox.partial i { display: block; }
.category-name { font-weight: 600; font-size: 14px; }
.category-right { display: flex; align-items: center; gap: 12px; }
.category-count { background: rgba(var(--primary-rgb), 0.15); color: var(--primary); padding: 4px 10px; border-radius: 20px; font-size: 11px; font-weight: 600; }
.category-toggle { color: var(--text-secondary); transition: transform 0.3s; }
.category-toggle.open { transform: rotate(180deg); }
.category-services { display: none; border-top: 1px solid var(--border-color); padding: 10px; background: rgba(0,0,0,0.1); }
.category-services.open { display: block; }

.service-item { display: flex; align-items: center; gap: 12px; padding: 10px 12px; border-radius: 8px; transition: background 0.2s; cursor: pointer; }
.service-item:hover { background: rgba(var(--primary-rgb), 0.1); }
.service-item.selected { background: rgba(var(--primary-rgb), 0.15); }
.service-item.existing { opacity: 0.6; }
.service-checkbox { width: 18px; height: 18px; border: 2px solid var(--border-color); border-radius: 4px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all 0.2s; }
.service-item.selected .service-checkbox { background: var(--primary); border-color: var(--primary); }
.service-checkbox i { color: #fff; font-size: 9px; display: none; }
.service-item.selected .service-checkbox i { display: block; }
.service-info { flex: 1; min-width: 0; }
.service-name { font-size: 12px; font-weight: 500; margin-bottom: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.service-meta { display: flex; gap: 10px; font-size: 10px; color: var(--text-secondary); }
.service-id { color: var(--primary); font-family: monospace; font-weight: 600; font-size: 11px; }
.service-rate { color: #10b981; font-weight: 600; font-size: 12px; white-space: nowrap; }
.service-badge { padding: 3px 8px; border-radius: 4px; font-size: 9px; font-weight: 600; }
.service-badge.existing { background: rgba(245,158,11,0.15); color: #f59e0b; }
.service-badge.new { background: rgba(16,185,129,0.15); color: #10b981; }

.services-footer { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 15px; padding-top: 15px; border-top: 1px solid var(--border-color); margin-top: 20px; }
.selected-count { font-size: 14px; color: var(--text-secondary); }
.selected-count strong { color: var(--primary); font-size: 18px; }
.save-options { display: flex; gap: 10px; }
.save-options .btn { padding: 12px 24px; border-radius: 8px; font-size: 13px; font-weight: 600; border: none; cursor: pointer; display: flex; align-items: center; gap: 8px; }
.btn-save-add { background: rgba(16,185,129,0.15); color: #10b981; }
.btn-save-add:hover { background: #10b981; color: #fff; }
.btn-save-replace { background: var(--gradient); color: #fff; }
.btn-save-replace:hover { opacity: 0.9; }

@media (max-width: 768px) {
    .providers-grid { grid-template-columns: 1fr; }
    .provider-stats { grid-template-columns: 1fr; }
    .provider-actions { grid-template-columns: repeat(2, 1fr); }
    .services-header { flex-direction: column; align-items: stretch; }
    .services-search { width: 100%; }
    .services-actions { justify-content: center; flex-wrap: wrap; }
    .services-footer { flex-direction: column; text-align: center; }
    .save-options { width: 100%; flex-direction: column; }
}
</style>

<div class="page-header">
    <h2><i class="fas fa-plug"></i> API Sağlayıcıları</h2>
    <?php if (!$demoMode): ?>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fas fa-plus"></i> Yeni Sağlayıcı
    </button>
    <?php else: ?>
    <button class="btn-primary-custom" disabled style="opacity: 0.5; cursor: not-allowed;">
        <i class="fas fa-lock"></i> Demo Mod
    </button>
    <?php endif; ?>
</div>

<?php if ($demoMode): ?>
<div class="demo-banner">
    <i class="fas fa-shield-alt"></i>
    <div class="demo-banner-text">
        <h4>Demo Modu Aktif</h4>
        <p>API anahtarları ve URL'ler güvenlik nedeniyle gizlenmiştir. Düzenleme işlemleri devre dışıdır.</p>
    </div>
</div>
<?php endif; ?>

<?php if (empty($providers)): ?>
<div class="empty-state">
    <i class="fas fa-plug"></i>
    <h3>Henüz API sağlayıcı eklenmemiş</h3>
    <p>Dış SMM panellerden servis çekmek için API sağlayıcı ekleyin.</p>
    <?php if (!$demoMode): ?>
    <button class="btn-primary-custom" data-bs-toggle="modal" data-bs-target="#addModal">
        <i class="fas fa-plus me-2"></i> İlk Sağlayıcıyı Ekle
    </button>
    <?php endif; ?>
</div>
<?php else: ?>
<div class="providers-grid">
    <?php foreach ($providers as $provider): 
        $currencySymbol = getCurrencySymbol($provider['currency']);
    ?>
    <div class="provider-card">
        <div class="provider-header">
            <div class="provider-info">
                <div class="provider-icon">
                    <i class="fas fa-server"></i>
                </div>
                <div>
                    <h3 class="provider-name"><?php echo clean($provider['name']); ?></h3>
                    <div class="provider-url <?php echo $demoMode ? 'masked' : ''; ?>">
                        <?php echo $demoMode ? maskSensitiveData($provider['api_url'], 8) : clean($provider['api_url']); ?>
                    </div>
                </div>
            </div>
            <span class="provider-status <?php echo $provider['status']; ?>">
                <?php echo $provider['status'] === 'active' ? 'Aktif' : 'Pasif'; ?>
            </span>
        </div>
        
        <div class="provider-body">
            <div class="provider-stats">
                <div class="provider-stat">
                    <div class="provider-stat-value balance"><?php echo number_format($provider['balance'], 2, ',', '.'); ?></div>
                    <div class="provider-stat-label"><?php echo $currencySymbol; ?> Bakiye</div>
                </div>
                <div class="provider-stat">
                    <div class="provider-stat-value"><?php echo $provider['service_count']; ?></div>
                    <div class="provider-stat-label">Kayıtlı Servis</div>
                </div>
                <div class="provider-stat">
                    <div class="provider-stat-value"><?php echo $provider['rate_multiplier']; ?>x</div>
                    <div class="provider-stat-label">Fiyat Çarpanı</div>
                </div>
            </div>
            
            <div class="provider-meta">
                <div class="provider-meta-item">
                    <i class="fas fa-key"></i>
                    <span>API Key: <?php echo $demoMode ? maskSensitiveData($provider['api_key'], 4) : '••••••••••••'; ?></span>
                </div>
                <div class="provider-meta-item">
                    <i class="fas fa-clock"></i>
                    <span>Son Sync: <?php echo $provider['last_sync_at'] ? date('d.m.Y H:i', strtotime($provider['last_sync_at'])) : 'Hiç'; ?></span>
                </div>
            </div>
            
            <div class="provider-actions">
                <?php if (!$demoMode): ?>
                <form method="POST" style="display: contents;">
                    <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                    <input type="hidden" name="provider_id" value="<?php echo $provider['id']; ?>">
                    <button type="submit" name="action" value="sync_balance" class="btn btn-sync">
                        <i class="fas fa-sync-alt"></i> Bakiye
                    </button>
                </form>
                <button class="btn btn-add-services" onclick="openAddServicesModal(<?php echo $provider['id']; ?>, '<?php echo clean($provider['name']); ?>', '<?php echo $provider['currency']; ?>')">
                    <i class="fas fa-plus"></i> Servis Ekle
                </button>
                <button class="btn btn-view-services" onclick="openViewServicesModal(<?php echo $provider['id']; ?>, '<?php echo clean($provider['name']); ?>', '<?php echo $provider['currency']; ?>')">
                    <i class="fas fa-list"></i> Servisler (<?php echo $provider['service_count']; ?>)
                </button>
                <button class="btn btn-edit" onclick="editProvider(<?php echo htmlspecialchars(json_encode($provider)); ?>)">
                    <i class="fas fa-edit"></i> Düzenle
                </button>
                <button class="btn btn-delete" onclick="deleteProvider(<?php echo $provider['id']; ?>, '<?php echo clean($provider['name']); ?>')">
                    <i class="fas fa-trash"></i> Sil
                </button>
                <?php else: ?>
                <button class="btn btn-sync disabled" disabled><i class="fas fa-lock"></i></button>
                <button class="btn btn-add-services disabled" disabled><i class="fas fa-lock"></i></button>
                <button class="btn btn-view-services" onclick="openViewServicesModal(<?php echo $provider['id']; ?>, '<?php echo clean($provider['name']); ?>', '<?php echo $provider['currency']; ?>')">
                    <i class="fas fa-list"></i> Görüntüle
                </button>
                <button class="btn btn-edit disabled" disabled><i class="fas fa-lock"></i></button>
                <button class="btn btn-delete disabled" disabled><i class="fas fa-lock"></i></button>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php if (!$demoMode): ?>
<!-- Add Provider Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="add_provider">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus me-2"></i>Yeni API Sağlayıcı</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Sağlayıcı Adı *</label>
                        <input type="text" name="name" class="form-control" placeholder="Örn: SMMPanel.com" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API URL *</label>
                        <input type="url" name="api_url" class="form-control" placeholder="https://smmpanel.com/api/v2" required>
                        <div class="form-text">Genellikle /api/v2 şeklinde biter</div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API Key *</label>
                        <input type="text" name="api_key" class="form-control" placeholder="API anahtarınız" required>
                    </div>
                    <div class="row">
                        <div class="col-6">
                            <label class="form-label">Para Birimi</label>
                            <select name="currency" class="form-select">
                                <option value="TRY" selected>TRY (₺)</option>
                                <option value="USD">USD ($)</option>
                                <option value="EUR">EUR (€)</option>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label">Fiyat Çarpanı</label>
                            <input type="number" name="rate_multiplier" class="form-control" value="1.5" step="0.1" min="1">
                            <div class="form-text">Örn: 1.5 = %50 kâr</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom"><i class="fas fa-plug me-1"></i> Bağlan ve Ekle</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Provider Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                <input type="hidden" name="action" value="update_provider">
                <input type="hidden" name="provider_id" id="editProviderId">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Sağlayıcı Düzenle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Sağlayıcı Adı *</label>
                        <input type="text" name="name" id="editName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API URL *</label>
                        <input type="url" name="api_url" id="editApiUrl" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">API Key *</label>
                        <input type="text" name="api_key" id="editApiKey" class="form-control" required>
                    </div>
                    <div class="row">
                        <div class="col-4">
                            <label class="form-label">Para Birimi</label>
                            <select name="currency" id="editCurrency" class="form-select">
                                <option value="TRY">TRY (₺)</option>
                                <option value="USD">USD ($)</option>
                                <option value="EUR">EUR (€)</option>
                            </select>
                        </div>
                        <div class="col-4">
                            <label class="form-label">Çarpan</label>
                            <input type="number" name="rate_multiplier" id="editRate" class="form-control" step="0.1" min="1">
                        </div>
                        <div class="col-4">
                            <label class="form-label">Durum</label>
                            <select name="status" id="editStatus" class="form-select">
                                <option value="active">Aktif</option>
                                <option value="inactive">Pasif</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn-secondary-custom" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn-primary-custom"><i class="fas fa-save me-1"></i> Kaydet</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Add Services Modal (API'den Çek) -->
<div class="modal fade" id="addServicesModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Servis Ekle - <span id="addServicesProviderName"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
            </div>
            <div class="modal-body">
                <div class="services-loading" id="addServicesLoading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>API'den servisler çekiliyor...</p>
                </div>
                
                <div id="addServicesContent" style="display: none;">
                    <div class="services-header">
                        <div class="services-stats">
                            <div class="services-stat">
                                <div class="services-stat-value" id="addTotalCount">0</div>
                                <div class="services-stat-label">API'deki Toplam</div>
                            </div>
                            <div class="services-stat">
                                <div class="services-stat-value" id="addCategoryCount">0</div>
                                <div class="services-stat-label">Kategori</div>
                            </div>
                            <div class="services-stat">
                                <div class="services-stat-value" id="addExistingCount">0</div>
                                <div class="services-stat-label">Zaten Ekli</div>
                            </div>
                        </div>
                        
                        <div class="services-search">
                            <i class="fas fa-search"></i>
                            <input type="text" id="addServicesSearch" placeholder="Servis ara...">
                        </div>
                        
                        <div class="services-actions">
                            <button class="btn btn-select-all" onclick="addSelectAll()">
                                <i class="fas fa-check-double"></i> Tümünü Seç
                            </button>
                            <button class="btn btn-deselect-all" onclick="addDeselectAll()">
                                <i class="fas fa-times"></i> Seçimi Kaldır
                            </button>
                        </div>
                    </div>
                    
                    <div class="categories-container" id="addCategoriesContainer"></div>
                    
                    <div class="services-footer">
                        <div class="selected-count">
                            <strong id="addSelectedCount">0</strong> servis seçildi
                        </div>
                        <div class="save-options">
                            <button class="btn btn-save-add" onclick="saveNewServices('add')" id="btnAddSave">
                                <i class="fas fa-plus"></i> Mevcut Listeye Ekle
                            </button>
                            <button class="btn btn-save-replace" onclick="saveNewServices('replace')" id="btnReplaceSave">
                                <i class="fas fa-sync-alt"></i> Tümünü Değiştir
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="addServicesError" style="display: none; text-align: center; padding: 40px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ef4444; margin-bottom: 15px;"></i>
                    <p id="addServicesErrorText" style="color: #ef4444;"></p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- View/Manage Existing Services Modal -->
<div class="modal fade" id="viewServicesModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-list me-2"></i>Kayıtlı Servisler - <span id="viewServicesProviderName"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
            </div>
            <div class="modal-body">
                <div class="services-loading" id="viewServicesLoading">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>Servisler yükleniyor...</p>
                </div>
                
                <div id="viewServicesContent" style="display: none;">
                    <div class="services-header">
                        <div class="services-stats">
                            <div class="services-stat">
                                <div class="services-stat-value" id="viewTotalCount">0</div>
                                <div class="services-stat-label">Toplam Servis</div>
                            </div>
                            <div class="services-stat">
                                <div class="services-stat-value" id="viewCategoryCount">0</div>
                                <div class="services-stat-label">Kategori</div>
                            </div>
                        </div>
                        
                        <div class="services-search">
                            <i class="fas fa-search"></i>
                            <input type="text" id="viewServicesSearch" placeholder="Servis ara...">
                        </div>
                        
                        <?php if (!$demoMode): ?>
                        <div class="services-actions">
                            <button class="btn btn-select-all" onclick="viewSelectAll()">
                                <i class="fas fa-check-double"></i> Tümünü Seç
                            </button>
                            <button class="btn btn-deselect-all" onclick="viewDeselectAll()">
                                <i class="fas fa-times"></i> Seçimi Kaldır
                            </button>
                            <button class="btn btn-delete-selected" onclick="deleteSelectedServices()" id="btnDeleteSelected">
                                <i class="fas fa-trash"></i> Seçilenleri Sil
                            </button>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="categories-container" id="viewCategoriesContainer"></div>
                    
                    <?php if (!$demoMode): ?>
                    <div class="services-footer">
                        <div class="selected-count">
                            <strong id="viewSelectedCount">0</strong> servis seçildi
                        </div>
                        <div class="save-options">
                            <form method="POST" style="display: inline;" onsubmit="return confirm('Tüm servisleri silmek istediğinize emin misiniz?');">
                                <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
                                <input type="hidden" name="action" value="delete_all_services">
                                <input type="hidden" name="provider_id" id="viewDeleteAllProviderId">
                                <button type="submit" class="btn btn-delete-selected">
                                    <i class="fas fa-trash-alt"></i> Tüm Servisleri Sil
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php else: ?>
                    <div class="services-footer">
                        <div class="selected-count" style="width: 100%; text-align: center;">
                            <i class="fas fa-lock" style="color: #f59e0b; margin-right: 8px;"></i>
                            Demo modunda silme işlemi yapılamaz.
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <div id="viewServicesEmpty" style="display: none; text-align: center; padding: 60px;">
                    <i class="fas fa-inbox" style="font-size: 48px; color: var(--text-secondary); opacity: 0.3; margin-bottom: 15px;"></i>
                    <p style="color: var(--text-secondary);">Bu sağlayıcıya henüz servis eklenmemiş.</p>
                </div>
                
                <div id="viewServicesError" style="display: none; text-align: center; padding: 40px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #ef4444; margin-bottom: 15px;"></i>
                    <p id="viewServicesErrorText" style="color: #ef4444;"></p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';
var demoMode = <?php echo $demoMode ? 'true' : 'false'; ?>;

// Para birimi sembolleri
var currencySymbols = {
    'TRY': '₺',
    'USD': '$',
    'EUR': '€',
    'GBP': '£'
};

function getCurrencySymbol(currency) {
    return currencySymbols[currency] || currency;
}

// Fiyat formatlama fonksiyonu
function formatRate(rate, currency) {
    var symbol = getCurrencySymbol(currency);
    var formatted = parseFloat(rate).toLocaleString('tr-TR', {
        minimumFractionDigits: 4,
        maximumFractionDigits: 4
    });
    return formatted + ' ' + symbol;
}

// Add Services Modal Variables
var addProviderId = null;
var addProviderCurrency = 'TRY';
var addCategories = [];
var addSelectedServices = [];
var addExistingServices = [];

// View Services Modal Variables
var viewProviderId = null;
var viewProviderCurrency = 'TRY';
var viewCategories = [];
var viewSelectedIds = [];

// ==================== PROVIDER FUNCTIONS ====================
<?php if (!$demoMode): ?>
function editProvider(provider) {
    document.getElementById('editProviderId').value = provider.id;
    document.getElementById('editName').value = provider.name;
    document.getElementById('editApiUrl').value = provider.api_url;
    document.getElementById('editApiKey').value = provider.api_key;
    document.getElementById('editCurrency').value = provider.currency;
    document.getElementById('editRate').value = provider.rate_multiplier;
    document.getElementById('editStatus').value = provider.status;
    new bootstrap.Modal(document.getElementById('editModal')).show();
}

function deleteProvider(id, name) {
    Swal.fire({
        title: 'Sağlayıcıyı silmek istediğinize emin misiniz?',
        text: '"' + name + '" ve tüm servisleri silinecek!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Sil!',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="delete_provider">' +
                '<input type="hidden" name="provider_id" value="' + id + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}
<?php endif; ?>

// ==================== ADD SERVICES MODAL ====================
function openAddServicesModal(providerId, providerName, currency) {
    addProviderId = providerId;
    addProviderCurrency = currency || 'TRY';
    addSelectedServices = [];
    
    document.getElementById('addServicesProviderName').textContent = providerName;
    document.getElementById('addServicesLoading').style.display = 'block';
    document.getElementById('addServicesContent').style.display = 'none';
    document.getElementById('addServicesError').style.display = 'none';
    
    new bootstrap.Modal(document.getElementById('addServicesModal')).show();
    
    fetch('?ajax=get_services&provider_id=' + providerId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            document.getElementById('addServicesLoading').style.display = 'none';
            
            if (!data.success) {
                document.getElementById('addServicesError').style.display = 'block';
                document.getElementById('addServicesErrorText').textContent = data.error;
                return;
            }
            
            addCategories = data.categories;
            addExistingServices = data.existing || [];
            addProviderCurrency = data.currency || 'TRY';
            
            document.getElementById('addTotalCount').textContent = data.total;
            document.getElementById('addCategoryCount').textContent = data.categories.length;
            document.getElementById('addExistingCount').textContent = addExistingServices.length;
            
            renderAddCategories();
            document.getElementById('addServicesContent').style.display = 'block';
        })
        .catch(function(err) {
            document.getElementById('addServicesLoading').style.display = 'none';
            document.getElementById('addServicesError').style.display = 'block';
            document.getElementById('addServicesErrorText').textContent = 'Bağlantı hatası: ' + err.message;
        });
}

function renderAddCategories(filter) {
    var container = document.getElementById('addCategoriesContainer');
    var html = '';
    
    addCategories.forEach(function(cat, catIndex) {
        var services = cat.services;
        if (filter) {
            filter = filter.toLowerCase();
            services = cat.services.filter(function(s) {
                return s.name.toLowerCase().indexOf(filter) !== -1 || s.id.toString().indexOf(filter) !== -1;
            });
        }
        if (services.length === 0) return;
        
        var selectedInCat = services.filter(function(s) {
            return addSelectedServices.some(function(ss) { return ss.id === s.id; });
        }).length;
        
        var checkClass = selectedInCat === services.length ? 'checked' : selectedInCat > 0 ? 'partial' : '';
        var checkIcon = checkClass === 'partial' ? 'fa-minus' : 'fa-check';
        
        html += '<div class="category-item">';
        html += '<div class="category-header" onclick="toggleAddCategory(' + catIndex + ')">';
        html += '<div class="category-left">';
        html += '<div class="category-checkbox ' + checkClass + '" onclick="event.stopPropagation(); toggleAddCategorySelect(' + catIndex + ')"><i class="fas ' + checkIcon + '"></i></div>';
        html += '<span class="category-name">' + cat.name + '</span></div>';
        html += '<div class="category-right"><span class="category-count">' + selectedInCat + ' / ' + services.length + '</span>';
        html += '<i class="fas fa-chevron-down category-toggle" id="addCatToggle' + catIndex + '"></i></div></div>';
        html += '<div class="category-services" id="addCatServices' + catIndex + '">';
        
        services.forEach(function(service) {
            var isSelected = addSelectedServices.some(function(s) { return s.id === service.id; });
            var isExisting = addExistingServices.indexOf(service.id.toString()) !== -1 || addExistingServices.indexOf(parseInt(service.id)) !== -1;
            
            var serviceJson = JSON.stringify(service).replace(/"/g, '&quot;');
            
            html += '<div class="service-item' + (isSelected ? ' selected' : '') + (isExisting ? ' existing' : '') + '" onclick="toggleAddService(' + serviceJson + ')">';
            html += '<div class="service-checkbox"><i class="fas fa-check"></i></div>';
            html += '<div class="service-info"><div class="service-name">' + service.name + '</div>';
            html += '<div class="service-meta"><span class="service-id">#' + service.id + '</span>';
            html += '<span>Min: ' + Number(service.min).toLocaleString('tr-TR') + '</span>';
            html += '<span>Max: ' + Number(service.max).toLocaleString('tr-TR') + '</span></div></div>';
            html += '<span class="service-rate">' + formatRate(service.rate, addProviderCurrency) + '</span>';
            if (isExisting) html += '<span class="service-badge existing">Ekli</span>';
            html += '</div>';
        });
        
        html += '</div></div>';
    });
    
    container.innerHTML = html || '<p style="text-align:center;color:var(--text-secondary);padding:40px;">Sonuç bulunamadı.</p>';
    updateAddSelectedCount();
}

function toggleAddCategory(index) {
    var el = document.getElementById('addCatServices' + index);
    var toggle = document.getElementById('addCatToggle' + index);
    el.classList.toggle('open');
    toggle.classList.toggle('open');
}

function toggleAddCategorySelect(index) {
    var cat = addCategories[index];
    var allSelected = cat.services.every(function(s) {
        return addSelectedServices.some(function(ss) { return ss.id === s.id; });
    });
    
    if (allSelected) {
        cat.services.forEach(function(s) {
            addSelectedServices = addSelectedServices.filter(function(ss) { return ss.id !== s.id; });
        });
    } else {
        cat.services.forEach(function(s) {
            if (!addSelectedServices.some(function(ss) { return ss.id === s.id; })) {
                addSelectedServices.push(s);
            }
        });
    }
    renderAddCategories(document.getElementById('addServicesSearch').value);
}

function toggleAddService(service) {
    var idx = -1;
    for (var i = 0; i < addSelectedServices.length; i++) {
        if (addSelectedServices[i].id === service.id) {
            idx = i;
            break;
        }
    }
    if (idx !== -1) {
        addSelectedServices.splice(idx, 1);
    } else {
        addSelectedServices.push(service);
    }
    renderAddCategories(document.getElementById('addServicesSearch').value);
}

function addSelectAll() {
    addSelectedServices = [];
    addCategories.forEach(function(cat) {
        cat.services.forEach(function(s) {
            addSelectedServices.push(s);
        });
    });
    renderAddCategories(document.getElementById('addServicesSearch').value);
}

function addDeselectAll() {
    addSelectedServices = [];
    renderAddCategories(document.getElementById('addServicesSearch').value);
}

function updateAddSelectedCount() {
    document.getElementById('addSelectedCount').textContent = addSelectedServices.length;
    var disabled = addSelectedServices.length === 0;
    document.getElementById('btnAddSave').disabled = disabled;
    document.getElementById('btnReplaceSave').disabled = disabled;
    document.getElementById('btnAddSave').style.opacity = disabled ? '0.5' : '1';
    document.getElementById('btnReplaceSave').style.opacity = disabled ? '0.5' : '1';
}

function saveNewServices(mode) {
    if (addSelectedServices.length === 0) return;
    
    var title = mode === 'add' ? 'Seçilen servisleri eklemek istiyor musunuz?' : 'Mevcut servisleri silip yenilerini eklemek istiyor musunuz?';
    
    Swal.fire({
        title: title,
        html: '<strong>' + addSelectedServices.length + '</strong> servis işlenecek.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: mode === 'add' ? '#10b981' : '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: mode === 'add' ? 'Ekle' : 'Değiştir',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Kaydediliyor...',
                allowOutsideClick: false,
                didOpen: function() { Swal.showLoading(); },
                background: '#1e293b',
                color: '#f8fafc'
            });
            
            var formData = new FormData();
            formData.append('ajax', 'save_services');
            formData.append('csrf_token', csrfToken);
            formData.append('provider_id', addProviderId);
            formData.append('services', JSON.stringify(addSelectedServices));
            formData.append('mode', mode);
            
            fetch('', { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Başarılı!',
                            text: data.count + ' servis kaydedildi.',
                            background: '#1e293b',
                            color: '#f8fafc'
                        }).then(function() { location.reload(); });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Hata!',
                            text: data.error,
                            background: '#1e293b',
                            color: '#f8fafc'
                        });
                    }
                })
                .catch(function(err) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Bağlantı Hatası',
                        text: err.message,
                        background: '#1e293b',
                        color: '#f8fafc'
                    });
                });
        }
    });
}

// ==================== VIEW SERVICES MODAL ====================
function openViewServicesModal(providerId, providerName, currency) {
    viewProviderId = providerId;
    viewProviderCurrency = currency || 'TRY';
    viewSelectedIds = [];
    
    document.getElementById('viewServicesProviderName').textContent = providerName;
    document.getElementById('viewServicesLoading').style.display = 'block';
    document.getElementById('viewServicesContent').style.display = 'none';
    document.getElementById('viewServicesEmpty').style.display = 'none';
    document.getElementById('viewServicesError').style.display = 'none';
    
    if (document.getElementById('viewDeleteAllProviderId')) {
        document.getElementById('viewDeleteAllProviderId').value = providerId;
    }
    
    new bootstrap.Modal(document.getElementById('viewServicesModal')).show();
    
    fetch('?ajax=get_existing_services&provider_id=' + providerId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            document.getElementById('viewServicesLoading').style.display = 'none';
            
            if (!data.success) {
                document.getElementById('viewServicesError').style.display = 'block';
                document.getElementById('viewServicesErrorText').textContent = data.error;
                return;
            }
            
            if (data.total === 0) {
                document.getElementById('viewServicesEmpty').style.display = 'block';
                return;
            }
            
            viewCategories = data.categories;
            viewProviderCurrency = data.currency || 'TRY';
            
            document.getElementById('viewTotalCount').textContent = data.total;
            document.getElementById('viewCategoryCount').textContent = data.categories.length;
            
            renderViewCategories();
            document.getElementById('viewServicesContent').style.display = 'block';
        })
        .catch(function(err) {
            document.getElementById('viewServicesLoading').style.display = 'none';
            document.getElementById('viewServicesError').style.display = 'block';
            document.getElementById('viewServicesErrorText').textContent = 'Bağlantı hatası: ' + err.message;
        });
}

function renderViewCategories(filter) {
    var container = document.getElementById('viewCategoriesContainer');
    var html = '';
    
    viewCategories.forEach(function(cat, catIndex) {
        var services = cat.services;
        if (filter) {
            filter = filter.toLowerCase();
            services = cat.services.filter(function(s) {
                return s.name.toLowerCase().indexOf(filter) !== -1 || s.service_id.toString().indexOf(filter) !== -1;
            });
        }
        if (services.length === 0) return;
        
        var selectedInCat = services.filter(function(s) {
            return viewSelectedIds.indexOf(s.id) !== -1;
        }).length;
        
        var checkClass = selectedInCat === services.length ? 'checked' : selectedInCat > 0 ? 'partial' : '';
        var checkIcon = checkClass === 'partial' ? 'fa-minus' : 'fa-check';
        
        html += '<div class="category-item">';
        html += '<div class="category-header" onclick="toggleViewCategory(' + catIndex + ')">';
        html += '<div class="category-left">';
        
        if (!demoMode) {
            html += '<div class="category-checkbox ' + checkClass + '" onclick="event.stopPropagation(); toggleViewCategorySelect(' + catIndex + ')"><i class="fas ' + checkIcon + '"></i></div>';
        }
        
        html += '<span class="category-name">' + cat.name + '</span></div>';
        html += '<div class="category-right"><span class="category-count">' + services.length + ' servis</span>';
        html += '<i class="fas fa-chevron-down category-toggle" id="viewCatToggle' + catIndex + '"></i></div></div>';
        html += '<div class="category-services" id="viewCatServices' + catIndex + '">';
        
        services.forEach(function(service) {
            var isSelected = viewSelectedIds.indexOf(service.id) !== -1;
            
            if (!demoMode) {
                html += '<div class="service-item' + (isSelected ? ' selected' : '') + '" onclick="toggleViewService(' + service.id + ')">';
                html += '<div class="service-checkbox"><i class="fas fa-check"></i></div>';
            } else {
                html += '<div class="service-item">';
            }
            
            html += '<div class="service-info"><div class="service-name">' + service.name + '</div>';
            html += '<div class="service-meta"><span class="service-id">#' + service.service_id + '</span>';
            html += '<span>Min: ' + Number(service.min).toLocaleString('tr-TR') + '</span>';
            html += '<span>Max: ' + Number(service.max).toLocaleString('tr-TR') + '</span></div></div>';
            html += '<span class="service-rate">' + formatRate(service.rate, viewProviderCurrency) + '</span>';
            html += '</div>';
        });
        
        html += '</div></div>';
    });
    
    container.innerHTML = html || '<p style="text-align:center;color:var(--text-secondary);padding:40px;">Sonuç bulunamadı.</p>';
    
    if (!demoMode) updateViewSelectedCount();
}

function toggleViewCategory(index) {
    var el = document.getElementById('viewCatServices' + index);
    var toggle = document.getElementById('viewCatToggle' + index);
    el.classList.toggle('open');
    toggle.classList.toggle('open');
}

function toggleViewCategorySelect(index) {
    var cat = viewCategories[index];
    var allSelected = cat.services.every(function(s) {
        return viewSelectedIds.indexOf(s.id) !== -1;
    });
    
    if (allSelected) {
        cat.services.forEach(function(s) {
            viewSelectedIds = viewSelectedIds.filter(function(id) { return id !== s.id; });
        });
    } else {
        cat.services.forEach(function(s) {
            if (viewSelectedIds.indexOf(s.id) === -1) {
                viewSelectedIds.push(s.id);
            }
        });
    }
    renderViewCategories(document.getElementById('viewServicesSearch').value);
}

function toggleViewService(id) {
    var idx = viewSelectedIds.indexOf(id);
    if (idx !== -1) {
        viewSelectedIds.splice(idx, 1);
    } else {
        viewSelectedIds.push(id);
    }
    renderViewCategories(document.getElementById('viewServicesSearch').value);
}

function viewSelectAll() {
    viewSelectedIds = [];
    viewCategories.forEach(function(cat) {
        cat.services.forEach(function(s) {
            viewSelectedIds.push(s.id);
        });
    });
    renderViewCategories(document.getElementById('viewServicesSearch').value);
}

function viewDeselectAll() {
    viewSelectedIds = [];
    renderViewCategories(document.getElementById('viewServicesSearch').value);
}

function updateViewSelectedCount() {
    var el = document.getElementById('viewSelectedCount');
    if (el) el.textContent = viewSelectedIds.length;
    
    var btn = document.getElementById('btnDeleteSelected');
    if (btn) {
        btn.disabled = viewSelectedIds.length === 0;
        btn.style.opacity = viewSelectedIds.length === 0 ? '0.5' : '1';
    }
}

function deleteSelectedServices() {
    if (viewSelectedIds.length === 0) return;
    
    Swal.fire({
        title: 'Seçili servisleri silmek istiyor musunuz?',
        html: '<strong>' + viewSelectedIds.length + '</strong> servis silinecek.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: 'Evet, Sil!',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Siliniyor...',
                allowOutsideClick: false,
                didOpen: function() { Swal.showLoading(); },
                background: '#1e293b',
                color: '#f8fafc'
            });
            
            var formData = new FormData();
            formData.append('ajax', 'delete_selected_services');
            formData.append('csrf_token', csrfToken);
            formData.append('provider_id', viewProviderId);
            formData.append('service_ids', JSON.stringify(viewSelectedIds));
            
            fetch('', { method: 'POST', body: formData })
                .then(function(r) { return r.json(); })
                .then(function(data) {
                    if (data.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Silindi!',
                            text: data.count + ' servis silindi.',
                            background: '#1e293b',
                            color: '#f8fafc'
                        }).then(function() { location.reload(); });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Hata!',
                            text: data.error,
                            background: '#1e293b',
                            color: '#f8fafc'
                        });
                    }
                })
                .catch(function(err) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Bağlantı Hatası',
                        text: err.message,
                        background: '#1e293b',
                        color: '#f8fafc'
                    });
                });
        }
    });
}

// ==================== SEARCH EVENTS ====================
document.addEventListener('DOMContentLoaded', function() {
    var addSearch = document.getElementById('addServicesSearch');
    if (addSearch) {
        var timeout;
        addSearch.addEventListener('input', function() {
            clearTimeout(timeout);
            var val = this.value;
            timeout = setTimeout(function() { renderAddCategories(val); }, 300);
        });
    }
    
    var viewSearch = document.getElementById('viewServicesSearch');
    if (viewSearch) {
        var timeout2;
        viewSearch.addEventListener('input', function() {
            clearTimeout(timeout2);
            var val = this.value;
            timeout2 = setTimeout(function() { renderViewCategories(val); }, 300);
        });
    }
});
</script>

<?php require_once __DIR__ . '/footer.php'; ?>