<?php
/**
 * API Ayarları Yönetimi
 * Gemini API Key ve diğer API ayarları
 * Hem admin paneli hem de JSON API endpoint
 */

session_start();
require_once __DIR__ . '/config/database.php';

$page_title = 'API Ayarları';

// JSON API istekleri için (mobil uygulama) - SESSION KONTROLÜ YOK!
if (isset($_GET['action']) && ($_GET['action'] === 'get_gemini' || $_GET['action'] === 'get_all')) {
    // CORS headers
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type');
    header('Content-Type: application/json');
    
    try {
        $database = new Database();
        $db = $database->getConnection();
        
        if ($_GET['action'] === 'get_gemini') {
            // Gemini API Key'i getir
            $stmt = $db->prepare("SELECT api_key FROM api_config WHERE api_name = 'gemini_api' AND is_active = 1");
            $stmt->execute();
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($result && !empty($result['api_key'])) {
                echo json_encode([
                    'success' => true,
                    'api_key' => $result['api_key']
                ]);
            } else {
                echo json_encode([
                    'success' => false,
                    'message' => 'Aktif Gemini API Key bulunamadı'
                ]);
            }
        } elseif ($_GET['action'] === 'get_all') {
            // Tüm API'leri getir
            $stmt = $db->prepare("SELECT * FROM api_config ORDER BY api_name");
            $stmt->execute();
            $apis = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'apis' => $apis
            ]);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'API hatası: ' . $e->getMessage()
        ]);
    }
    exit();
}

// Admin session kontrolü (sadece admin paneli için)
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

// Database bağlantısı
$database = new Database();
$db = $database->getConnection();

// Form işleme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'update_gemini':
                    $apiKey = trim($_POST['gemini_api_key'] ?? '');
                    
                    if (empty($apiKey)) {
                        throw new Exception("API Key boş olamaz");
                    }
                    
                    // Gemini API Key'i güncelle
                    $stmt = $db->prepare("
                        UPDATE api_config 
                        SET api_key = ?, updated_at = CURRENT_TIMESTAMP 
                        WHERE api_name = 'gemini_api'
                    ");
                    
                    if ($stmt->execute([$apiKey])) {
                        $_SESSION['success_message'] = 'Gemini API Key başarıyla güncellendi';
                    } else {
                        throw new Exception("API Key güncellenirken hata oluştu");
                    }
                    break;
                    
                case 'add_api':
                    $apiName = trim($_POST['api_name'] ?? '');
                    $apiKey = trim($_POST['api_key'] ?? '');
                    $description = trim($_POST['description'] ?? '');
                    
                    if (empty($apiName) || empty($apiKey)) {
                        throw new Exception("API adı ve key alanları zorunludur");
                    }
                    
                    // Yeni API ekle
                    $stmt = $db->prepare("
                        INSERT INTO api_config (api_name, api_key, description) 
                        VALUES (?, ?, ?)
                    ");
                    
                    if ($stmt->execute([$apiName, $apiKey, $description])) {
                        $_SESSION['success_message'] = 'Yeni API başarıyla eklendi';
                    } else {
                        throw new Exception("API eklenirken hata oluştu");
                    }
                    break;
                    
                case 'delete_api':
                    $apiId = (int)($_POST['api_id'] ?? 0);
                    
                    if ($apiId <= 0) {
                        throw new Exception("Geçersiz API ID");
                    }
                    
                    // API'yi sil (Gemini API hariç)
                    $stmt = $db->prepare("
                        DELETE FROM api_config 
                        WHERE id = ? AND api_name != 'gemini_api'
                    ");
                    
                    if ($stmt->execute([$apiId])) {
                        $_SESSION['success_message'] = 'API başarıyla silindi';
                    } else {
                        throw new Exception("API silinirken hata oluştu");
                    }
                    break;
                    
                case 'toggle_api':
                    $apiId = (int)($_POST['api_id'] ?? 0);
                    $isActive = (int)($_POST['is_active'] ?? 0);
                    
                    if ($apiId <= 0) {
                        throw new Exception("Geçersiz API ID");
                    }
                    
                    // API durumunu değiştir
                    $stmt = $db->prepare("
                        UPDATE api_config 
                        SET is_active = ?, updated_at = CURRENT_TIMESTAMP 
                        WHERE id = ?
                    ");
                    
                    if ($stmt->execute([$isActive, $apiId])) {
                        $status = $isActive ? 'aktif' : 'pasif';
                        $_SESSION['success_message'] = "API başarıyla $status yapıldı";
                    } else {
                        throw new Exception("API durumu değiştirilirken hata oluştu");
                    }
                    break;
            }
        }
        
        header('Location: api-settings.php');
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Tüm API'leri getir
$apis = [];
try {
    $stmt = $db->prepare("SELECT * FROM api_config ORDER BY api_name");
    $stmt->execute();
    $apis = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("API listesi getirme hatası: " . $e->getMessage());
}

include 'includes/header.php';
?>

<div class="page-header">
    <h2>API Ayarları</h2>
    <p>Uygulama API anahtarlarını yönetin</p>
</div>

<div class="api-container">
    <!-- Gemini API Ayarları -->
    <div class="api-card primary">
        <div class="api-header">
            <h3>
                <i class="fas fa-robot"></i>
                Google Gemini AI API
            </h3>
            <span class="api-status active">Aktif</span>
        </div>
        
        <div class="api-description">
            <p>Chat özelliği için kullanılan Google Gemini AI API anahtarı. Bu API olmadan chat özelliği çalışmaz.</p>
            <div class="api-info-box">
                <strong>Endpoint:</strong> <code>http://yoldurumu.net/admin/api-settings.php?action=get_gemini</code>
            </div>
        </div>
        
        <form method="POST" class="api-form">
            <input type="hidden" name="action" value="update_gemini">
            
            <div class="form-group">
                <label for="gemini_api_key">API Key *</label>
                <div class="input-group">
                    <input type="password" id="gemini_api_key" name="gemini_api_key" required 
                           placeholder="Google Gemini API Key'inizi girin"
                           value="<?php echo isset($apis[0]) && $apis[0]['api_name'] === 'gemini_api' ? htmlspecialchars($apis[0]['api_key']) : ''; ?>">
                    <button type="button" class="btn-toggle-password" onclick="togglePassword('gemini_api_key')">
                        <i class="fas fa-eye"></i>
                    </button>
                </div>
                <small>Google AI Studio'dan alabilirsiniz: <a href="https://aistudio.google.com/app/apikey" target="_blank">aistudio.google.com</a></small>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save"></i>
                    Gemini API Key'i Güncelle
                </button>
            </div>
        </form>
    </div>
    
    <!-- Diğer API'ler -->
    <div class="api-card">
        <div class="api-header">
            <h3>
                <i class="fas fa-cogs"></i>
                Diğer API'ler
            </h3>
            <button type="button" class="btn btn-secondary" onclick="toggleAddApiForm()">
                <i class="fas fa-plus"></i>
                Yeni API Ekle
            </button>
        </div>
        
        <!-- Yeni API Ekleme Formu -->
        <div id="addApiForm" class="add-api-form" style="display: none;">
            <form method="POST">
                <input type="hidden" name="action" value="add_api">
                
                <div class="form-row">
                    <div class="form-group">
                        <label for="api_name">API Adı *</label>
                        <input type="text" id="api_name" name="api_name" required 
                               placeholder="Örn: openai_api">
                    </div>
                    
                    <div class="form-group">
                        <label for="api_key">API Key *</label>
                        <input type="text" id="api_key" name="api_key" required 
                               placeholder="API anahtarını girin">
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="description">Açıklama</label>
                    <input type="text" id="description" name="description" 
                           placeholder="API açıklaması">
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-plus"></i>
                        API Ekle
                    </button>
                    <button type="button" class="btn btn-secondary" onclick="toggleAddApiForm()">
                        İptal
                    </button>
                </div>
            </form>
        </div>
        
        <!-- API Listesi -->
        <div class="api-list">
            <?php if (count($apis) > 1 || (count($apis) === 1 && $apis[0]['api_name'] !== 'gemini_api')): ?>
                <?php foreach ($apis as $api): ?>
                    <?php if ($api['api_name'] === 'gemini_api') continue; ?>
                    <div class="api-item">
                        <div class="api-info">
                            <div class="api-name"><?php echo htmlspecialchars($api['api_name']); ?></div>
                            <div class="api-desc"><?php echo htmlspecialchars($api['description'] ?? 'Açıklama yok'); ?></div>
                            <div class="api-key">
                                <span class="key-preview"><?php echo substr($api['api_key'], 0, 10) . '...'; ?></span>
                            </div>
                        </div>
                        
                        <div class="api-actions">
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="action" value="toggle_api">
                                <input type="hidden" name="api_id" value="<?php echo $api['id']; ?>">
                                <input type="hidden" name="is_active" value="<?php echo $api['is_active'] ? 0 : 1; ?>">
                                <button type="submit" class="btn btn-sm <?php echo $api['is_active'] ? 'btn-warning' : 'btn-success'; ?>">
                                    <i class="fas <?php echo $api['is_active'] ? 'fa-pause' : 'fa-play'; ?>"></i>
                                    <?php echo $api['is_active'] ? 'Pasif Yap' : 'Aktif Yap'; ?>
                                </button>
                            </form>
                            
                            <form method="POST" style="display: inline;" onsubmit="return confirm('Bu API\'yi silmek istediğinizden emin misiniz?')">
                                <input type="hidden" name="action" value="delete_api">
                                <input type="hidden" name="api_id" value="<?php echo $api['id']; ?>">
                                <button type="submit" class="btn btn-sm btn-danger">
                                    <i class="fas fa-trash"></i>
                                    Sil
                                </button>
                            </form>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="no-apis">
                    <i class="fas fa-info-circle"></i>
                    <p>Henüz ek API eklenmemiş</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
function togglePassword(inputId) {
    const input = document.getElementById(inputId);
    const button = input.nextElementSibling;
    const icon = button.querySelector('i');
    
    if (input.type === 'password') {
        input.type = 'text';
        icon.className = 'fas fa-eye-slash';
    } else {
        input.type = 'password';
        icon.className = 'fas fa-eye';
    }
}

function toggleAddApiForm() {
    const form = document.getElementById('addApiForm');
    if (form.style.display === 'none' || form.style.display === '') {
        form.style.display = 'block';
    } else {
        form.style.display = 'none';
    }
}
</script>

<style>
.api-container {
    display: flex;
    flex-direction: column;
    gap: 2rem;
    margin-top: 1rem;
}

.api-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border: 2px solid #e5e7eb;
}

.api-card.primary {
    border-color: #4f46e5;
    background: linear-gradient(135deg, #f8fafc, #f1f5f9);
}

.api-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #e5e7eb;
}

.api-header h3 {
    margin: 0;
    color: #1f2937;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.api-status {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
    text-transform: uppercase;
}

.api-status.active {
    background: #d1fae5;
    color: #065f46;
}

.api-status.inactive {
    background: #fee2e2;
    color: #991b1b;
}

.api-description {
    margin-bottom: 1.5rem;
    padding: 1rem;
    background: #f9fafb;
    border-radius: 8px;
    border-left: 4px solid #4f46e5;
}

.api-description p {
    margin: 0 0 1rem 0;
    color: #6b7280;
    line-height: 1.5;
}

.api-info-box {
    background: #e0e7ff;
    padding: 0.75rem;
    border-radius: 6px;
    font-size: 0.9rem;
}

.api-info-box code {
    background: #1f2937;
    color: #f9fafb;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
    font-family: monospace;
    font-size: 0.8rem;
}

.api-form {
    margin-bottom: 1rem;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #333;
}

.input-group {
    position: relative;
    display: flex;
}

.input-group input {
    flex: 1;
    padding: 0.75rem;
    border: 2px solid #e1e5e9;
    border-radius: 8px 0 0 8px;
    font-size: 0.9rem;
}

.btn-toggle-password {
    padding: 0.75rem 1rem;
    border: 2px solid #e1e5e9;
    border-left: none;
    border-radius: 0 8px 8px 0;
    background: #f9fafb;
    color: #6b7280;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-toggle-password:hover {
    background: #f3f4f6;
    color: #374151;
}

.form-group input, .form-group select, .form-group textarea {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    font-size: 0.9rem;
    transition: border-color 0.3s;
}

.form-group input:focus, .form-group select:focus, .form-group textarea:focus {
    outline: none;
    border-color: #4f46e5;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
}

.form-actions {
    display: flex;
    gap: 1rem;
    margin-top: 1.5rem;
}

.btn {
    padding: 0.75rem 1.5rem;
    border: none;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.3s;
    text-decoration: none;
}

.btn-primary {
    background: linear-gradient(135deg, #4f46e5, #7c3aed);
    color: white;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(79, 70, 229, 0.4);
}

.btn-secondary {
    background: #f3f4f6;
    color: #374151;
}

.btn-secondary:hover {
    background: #e5e7eb;
}

.btn-sm {
    padding: 0.5rem 1rem;
    font-size: 0.8rem;
}

.btn-success {
    background: #10b981;
    color: white;
}

.btn-warning {
    background: #f59e0b;
    color: white;
}

.btn-danger {
    background: #ef4444;
    color: white;
}

.add-api-form {
    margin-bottom: 1.5rem;
    padding: 1.5rem;
    background: #f9fafb;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
}

.api-list {
    max-height: 400px;
    overflow-y: auto;
}

.api-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 8px;
    margin-bottom: 0.75rem;
    background: #f9fafb;
}

.api-info {
    flex: 1;
}

.api-name {
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.api-desc {
    color: #6b7280;
    font-size: 0.9rem;
    margin-bottom: 0.25rem;
}

.api-key {
    font-family: monospace;
    font-size: 0.8rem;
    color: #9ca3af;
}

.key-preview {
    background: #e5e7eb;
    padding: 0.25rem 0.5rem;
    border-radius: 4px;
}

.api-actions {
    display: flex;
    gap: 0.5rem;
}

.no-apis {
    text-align: center;
    padding: 2rem;
    color: #6b7280;
}

.no-apis i {
    font-size: 2rem;
    margin-bottom: 1rem;
    color: #9ca3af;
}

@media (max-width: 768px) {
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .api-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }
    
    .api-actions {
        width: 100%;
        justify-content: flex-end;
    }
    
    .form-actions {
        flex-direction: column;
    }
}
</style>

<?php include 'includes/footer.php'; ?>
