<?php
/**
 * SMM Paket Satış Scripti - API Servisleri
 * @version 1.0.0
 */

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

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

$providerId = (int)($_GET['provider'] ?? 0);

// Sağlayıcıyı kontrol et
if ($providerId > 0) {
    try {
        $stmt = $db->prepare("SELECT * FROM api_providers WHERE id = ?");
        $stmt->execute([$providerId]);
        $provider = $stmt->fetch();
    } catch (PDOException $e) {
        $provider = null;
    }
}

// Servis paket olarak ekle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'import_service') {
    $serviceId = (int)$_POST['service_id'];
    
    try {
        $stmt = $db->prepare("SELECT s.*, p.id as provider_id, p.rate_multiplier, p.currency 
                              FROM api_services s 
                              JOIN api_providers p ON s.provider_id = p.id 
                              WHERE s.id = ?");
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch();
        
        if ($service) {
            $categoryId = (int)$_POST['category_id'];
            $name = trim($_POST['name']);
            $description = trim($_POST['description']);
            $price = (float)$_POST['price'];
            $minQuantity = (int)$service['min'];
            $maxQuantity = (int)$service['max'];
            
            // Paketi oluştur
            $slug = createSlug($name);
            
            $stmt = $db->prepare("
                INSERT INTO packages (category_id, name, slug, description, price, quantity, delivery_time, 
                                      api_provider_id, api_service_id, is_active, created_at)
                VALUES (?, ?, ?, ?, ?, ?, '0-24 Saat', ?, ?, 1, NOW())
            ");
            $stmt->execute([
                $categoryId, 
                $name, 
                $slug, 
                $description, 
                $price, 
                $minQuantity,
                $service['provider_id'],
                $service['service_id']
            ]);
            
            // Servisi import edildi olarak işaretle
            $db->prepare("UPDATE api_services SET is_imported = 1 WHERE id = ?")->execute([$serviceId]);
            
            setFlash('success', 'Servis başarıyla paket olarak eklendi.');
        }
    } catch (PDOException $e) {
        setFlash('error', 'Hata: ' . $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/api-servisler.php?provider=' . $providerId);
    exit;
}

// Slug oluştur
function createSlug($text) {
    $text = mb_strtolower($text, 'UTF-8');
    $text = str_replace(['ı', 'ğ', 'ü', 'ş', 'ö', 'ç'], ['i', 'g', 'u', 's', 'o', 'c'], $text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim($text, '-');
    return $text . '-' . substr(uniqid(), -5);
}

// Sağlayıcıları çek
try {
    $providers = $db->query("SELECT * FROM api_providers WHERE status = 'active' ORDER BY name")->fetchAll();
} catch (PDOException $e) {
    $providers = [];
}

// Servisleri çek
$services = [];
$categories = [];
$searchQuery = trim($_GET['q'] ?? '');
$categoryFilter = $_GET['category'] ?? '';

if ($providerId > 0) {
    try {
        $where = "s.provider_id = ?";
        $params = [$providerId];
        
        if ($searchQuery) {
            $where .= " AND (s.name LIKE ? OR s.service_id LIKE ?)";
            $params[] = "%{$searchQuery}%";
            $params[] = "%{$searchQuery}%";
        }
        
        if ($categoryFilter) {
            $where .= " AND s.category = ?";
            $params[] = $categoryFilter;
        }
        
        $stmt = $db->prepare("SELECT s.* FROM api_services s WHERE $where ORDER BY s.category, s.service_id");
        $stmt->execute($params);
        $services = $stmt->fetchAll();
        
        // Kategorileri çek
        $catStmt = $db->prepare("SELECT DISTINCT category FROM api_services WHERE provider_id = ? ORDER BY category");
        $catStmt->execute([$providerId]);
        $serviceCategories = $catStmt->fetchAll(PDO::FETCH_COLUMN);
        
    } catch (PDOException $e) {
        $services = [];
        $serviceCategories = [];
    }
}

// Site kategorilerini çek
try {
    $siteCategories = $db->query("SELECT * FROM categories WHERE is_active = 1 ORDER BY sort_order")->fetchAll();
} catch (PDOException $e) {
    $siteCategories = [];
}

$adminPageTitle = 'API Servisleri';
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;
}

.filters-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    padding: 20px;
    margin-bottom: 20px;
}

.filters-row {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 180px;
}

.filter-group label {
    display: block;
    font-size: 12px;
    color: var(--text-secondary);
    margin-bottom: 6px;
}

.services-table {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 14px;
    overflow: hidden;
}

.table {
    margin: 0;
}

.table thead th {
    background: rgba(255,255,255,0.03);
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: var(--text-secondary);
    padding: 12px 15px;
    border-bottom: 1px solid var(--border-color);
    white-space: nowrap;
}

.table tbody td {
    padding: 12px 15px;
    border-bottom: 1px solid var(--border-color);
    font-size: 13px;
    vertical-align: middle;
}

.service-id {
    font-family: monospace;
    font-weight: 600;
    color: var(--primary);
}

.service-name {
    max-width: 300px;
}

.service-name-text {
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.service-category {
    display: inline-block;
    padding: 4px 10px;
    background: var(--bg-hover);
    border-radius: 6px;
    font-size: 11px;
    color: var(--text-secondary);
}

.service-rate {
    font-weight: 600;
    color: #10b981;
}

.service-minmax {
    font-size: 11px;
    color: var(--text-secondary);
}

.badge-imported {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 10px;
    background: rgba(16,185,129,0.15);
    color: #10b981;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
}

.btn-import {
    background: var(--gradient);
    border: none;
    color: #fff;
    padding: 6px 14px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}

.btn-import:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(var(--primary-rgb), 0.4);
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-secondary);
}

.empty-state i {
    font-size: 48px;
    opacity: 0.3;
    margin-bottom: 15px;
}

.stats-row {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.stat-box {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 15px 20px;
    display: flex;
    align-items: center;
    gap: 12px;
}

.stat-box-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
}

.stat-box-info h4 {
    font-size: 20px;
    font-weight: 700;
    margin: 0;
}

.stat-box-info span {
    font-size: 12px;
    color: var(--text-secondary);
}

/* Modal */
.modal-content {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
}

.modal-header {
    border-bottom: 1px solid var(--border-color);
    padding: 20px;
}

.modal-body {
    padding: 20px;
}

.modal-footer {
    border-top: 1px solid var(--border-color);
    padding: 15px 20px;
}

.service-preview {
    background: var(--bg-hover);
    border-radius: 10px;
    padding: 15px;
    margin-bottom: 20px;
}

.service-preview-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    font-size: 13px;
    border-bottom: 1px solid var(--border-color);
}

.service-preview-row:last-child {
    border-bottom: none;
}

.service-preview-label {
    color: var(--text-secondary);
}

.service-preview-value {
    font-weight: 600;
}

@media (max-width: 768px) {
    .filters-row {
        flex-direction: column;
    }
    
    .filter-group {
        width: 100%;
    }
    
    .stats-row {
        flex-direction: column;
    }
    
    .stat-box {
        width: 100%;
    }
}
</style>

<div class="page-header">
    <h2 style="font-size: 18px; margin: 0;">
        <i class="fas fa-list me-2" style="color: var(--primary);"></i>
        API Servisleri
    </h2>
    <a href="<?php echo SITE_URL; ?>/admin/api-saglayicilar.php" class="btn-secondary-custom">
        <i class="fas fa-arrow-left"></i> Sağlayıcılara Dön
    </a>
</div>

<!-- Filters -->
<div class="filters-card">
    <form method="GET" class="filters-row">
        <div class="filter-group">
            <label>API Sağlayıcı</label>
            <select name="provider" class="form-select" onchange="this.form.submit()">
                <option value="">-- Sağlayıcı Seçin --</option>
                <?php foreach ($providers as $p): ?>
                    <option value="<?php echo $p['id']; ?>" <?php echo $providerId == $p['id'] ? 'selected' : ''; ?>>
                        <?php echo clean($p['name']); ?> (<?php echo number_format($p['balance'], 2); ?> <?php echo $p['currency']; ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <?php if ($providerId > 0 && !empty($serviceCategories)): ?>
        <div class="filter-group">
            <label>Kategori</label>
            <select name="category" class="form-select" onchange="this.form.submit()">
                <option value="">Tüm Kategoriler</option>
                <?php foreach ($serviceCategories as $cat): ?>
                    <option value="<?php echo clean($cat); ?>" <?php echo $categoryFilter === $cat ? 'selected' : ''; ?>>
                        <?php echo clean($cat); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <?php endif; ?>
        
        <?php if ($providerId > 0): ?>
        <div class="filter-group" style="flex: 2;">
            <label>Servis Ara</label>
            <input type="text" name="q" class="form-control" placeholder="Servis adı veya ID..." value="<?php echo clean($searchQuery); ?>">
        </div>
        <div class="filter-group" style="flex: 0;">
            <label>&nbsp;</label>
            <button type="submit" class="btn-primary-custom" style="width: 100%;">
                <i class="fas fa-search"></i>
            </button>
        </div>
        <?php endif; ?>
    </form>
</div>

<?php if ($providerId > 0 && $provider): ?>
    <!-- Stats -->
    <div class="stats-row">
        <div class="stat-box">
            <div class="stat-box-icon" style="background: rgba(59,130,246,0.15); color: #3b82f6;">
                <i class="fas fa-server"></i>
            </div>
            <div class="stat-box-info">
                <h4><?php echo clean($provider['name']); ?></h4>
                <span>Sağlayıcı</span>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon" style="background: rgba(16,185,129,0.15); color: #10b981;">
                <i class="fas fa-wallet"></i>
            </div>
            <div class="stat-box-info">
                <h4><?php echo number_format($provider['balance'], 2); ?> <?php echo $provider['currency']; ?></h4>
                <span>Bakiye</span>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon" style="background: rgba(139,92,246,0.15); color: #8b5cf6;">
                <i class="fas fa-list"></i>
            </div>
            <div class="stat-box-info">
                <h4><?php echo count($services); ?></h4>
                <span>Servis</span>
            </div>
        </div>
        <div class="stat-box">
            <div class="stat-box-icon" style="background: rgba(245,158,11,0.15); color: #f59e0b;">
                <i class="fas fa-percentage"></i>
            </div>
            <div class="stat-box-info">
                <h4><?php echo $provider['rate_multiplier']; ?>x</h4>
                <span>Fiyat Çarpanı</span>
            </div>
        </div>
    </div>

    <!-- Services Table -->
    <div class="services-table">
        <?php if (empty($services)): ?>
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>Servis bulunamadı. Önce servisleri çekin.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Servis Adı</th>
                            <th>Kategori</th>
                            <th>Fiyat (1000)</th>
                            <th>Min/Max</th>
                            <th>Durum</th>
                            <th>İşlem</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($services as $service): 
                            $calculatedPrice = $service['rate'] * $provider['rate_multiplier'];
                        ?>
                        <tr>
                            <td><span class="service-id"><?php echo $service['service_id']; ?></span></td>
                            <td class="service-name">
                                <span class="service-name-text" title="<?php echo clean($service['name']); ?>">
                                    <?php echo clean($service['name']); ?>
                                </span>
                            </td>
                            <td><span class="service-category"><?php echo clean($service['category']); ?></span></td>
                            <td>
                                <span class="service-rate">$<?php echo number_format($service['rate'], 4); ?></span>
                                <br>
                                <small style="color: var(--text-secondary);">→ $<?php echo number_format($calculatedPrice, 4); ?></small>
                            </td>
                            <td>
                                <span class="service-minmax"><?php echo number_format($service['min']); ?> - <?php echo number_format($service['max']); ?></span>
                            </td>
                            <td>
                                <?php if ($service['is_imported']): ?>
                                    <span class="badge-imported"><i class="fas fa-check"></i> Eklendi</span>
                                <?php else: ?>
                                    <span style="color: var(--text-secondary); font-size: 12px;">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!$service['is_imported']): ?>
                                    <button class="btn-import" onclick="importService(<?php echo htmlspecialchars(json_encode([
                                        'id' => $service['id'],
                                        'service_id' => $service['service_id'],
                                        'name' => $service['name'],
                                        'category' => $service['category'],
                                        'rate' => $service['rate'],
                                        'calculated_rate' => $calculatedPrice,
                                        'min' => $service['min'],
                                        'max' => $service['max'],
                                        'currency' => $provider['currency']
                                    ])); ?>)">
                                        <i class="fas fa-plus"></i> Paket Ekle
                                    </button>
                                <?php else: ?>
                                    <button class="btn-import" style="background: var(--bg-hover); color: var(--text-secondary);" disabled>
                                        <i class="fas fa-check"></i> Eklendi
                                    </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
<?php else: ?>
    <div class="empty-state" style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 14px; padding: 80px 20px;">
        <i class="fas fa-hand-pointer" style="font-size: 60px;"></i>
        <h3 style="margin: 20px 0 10px;">Sağlayıcı Seçin</h3>
        <p>Servisleri görüntülemek için yukarıdan bir API sağlayıcı seçin.</p>
    </div>
<?php endif; ?>

<!-- Import Modal -->
<div class="modal fade" id="importModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="import_service">
                <input type="hidden" name="service_id" id="importServiceId">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Servisi Paket Olarak Ekle</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" style="filter: invert(1);"></button>
                </div>
                <div class="modal-body">
                    <div class="service-preview">
                        <div class="service-preview-row">
                            <span class="service-preview-label">API Servis ID:</span>
                            <span class="service-preview-value" id="previewServiceId"></span>
                        </div>
                        <div class="service-preview-row">
                            <span class="service-preview-label">Orijinal Ad:</span>
                            <span class="service-preview-value" id="previewName"></span>
                        </div>
                        <div class="service-preview-row">
                            <span class="service-preview-label">API Fiyatı (1K):</span>
                            <span class="service-preview-value" id="previewRate"></span>
                        </div>
                        <div class="service-preview-row">
                            <span class="service-preview-label">Min/Max:</span>
                            <span class="service-preview-value" id="previewMinMax"></span>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Site Kategorisi *</label>
                        <select name="category_id" class="form-select" required>
                            <option value="">-- Kategori Seçin --</option>
                            <?php foreach ($siteCategories as $cat): ?>
                                <option value="<?php echo $cat['id']; ?>"><?php echo clean($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Paket Adı *</label>
                        <input type="text" name="name" id="importName" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Açıklama</label>
                        <textarea name="description" id="importDescription" class="form-control" rows="2"></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Satış Fiyatı (₺) *</label>
                        <input type="number" name="price" id="importPrice" class="form-control" step="0.01" min="0.01" required>
                        <div class="form-text">Önerilen fiyat otomatik hesaplanmıştır (çarpan uygulanmış).</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-plus me-1"></i> Paket Olarak Ekle
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// USD to TRY kuru (gerçek projede API'den çekilmeli)
const usdToTry = 32.50;

function importService(service) {
    document.getElementById('importServiceId').value = service.id;
    document.getElementById('previewServiceId').textContent = service.service_id;
    document.getElementById('previewName').textContent = service.name;
    document.getElementById('previewRate').textContent = '$' + parseFloat(service.rate).toFixed(4) + ' → $' + parseFloat(service.calculated_rate).toFixed(4);
    document.getElementById('previewMinMax').textContent = service.min.toLocaleString() + ' - ' + service.max.toLocaleString();
    
    // Türkçeleştirilmiş isim öner
    document.getElementById('importName').value = service.name;
    document.getElementById('importDescription').value = 'Min: ' + service.min.toLocaleString() + ' - Max: ' + service.max.toLocaleString();
    
    // Fiyatı TL'ye çevir ve yuvarla
    let priceInTry = service.calculated_rate * usdToTry;
    // 1000'lik fiyatı min miktara göre hesapla
    let minPrice = (priceInTry / 1000) * service.min;
    // Yukarı yuvarla güzel bir sayıya
    minPrice = Math.ceil(minPrice / 5) * 5;
    if (minPrice < 1) minPrice = 1;
    
    document.getElementById('importPrice').value = minPrice.toFixed(2);
    
    new bootstrap.Modal(document.getElementById('importModal')).show();
}
</script>

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