<?php
/**
 * Kategoriler API Endpoint
 * Namaz Vakitleri Admin Panel
 * Mobil uygulama için kategoriler servisi
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// OPTIONS request için
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';

/**
 * JSON response gönder
 */
function sendResponse($success, $data = null, $message = '', $code = 200) {
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
    exit();
}

/**
 * Hata response gönder
 */
function sendError($message, $code = 400) {
    sendResponse(false, null, $message, $code);
}

try {
    $db = getDB();
    
    // Request method kontrolü
    if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
        sendError('Sadece GET metodu desteklenir', 405);
    }
    
    // Parametreleri al
    $include_counts = isset($_GET['include_counts']) ? (bool)$_GET['include_counts'] : false;
    $active_only = isset($_GET['active_only']) ? (bool)$_GET['active_only'] : true;
    
    // WHERE koşulunu oluştur
    $where_clause = $active_only ? 'WHERE sc.is_active = 1' : '';
    
    // Kategorileri al
    if ($include_counts) {
        $sql = "
            SELECT 
                sc.id,
                sc.name,
                sc.display_name,
                sc.description,
                sc.icon_name,
                sc.sort_order,
                sc.is_active,
                sc.created_at,
                COUNT(st.id) as story_count
            FROM story_categories sc 
            LEFT JOIN story_cards st ON sc.id = st.category_id AND st.is_active = 1
            $where_clause
            GROUP BY sc.id, sc.name, sc.display_name, sc.description, sc.icon_name, sc.sort_order, sc.is_active, sc.created_at
            ORDER BY sc.sort_order ASC, sc.display_name ASC
        ";
    } else {
        $sql = "
            SELECT 
                sc.id,
                sc.name,
                sc.display_name,
                sc.description,
                sc.icon_name,
                sc.sort_order,
                sc.is_active,
                sc.created_at
            FROM story_categories sc 
            $where_clause
            ORDER BY sc.sort_order ASC, sc.display_name ASC
        ";
    }
    
    $stmt = $db->query($sql);
    $categories = $stmt->fetchAll();
    
    // Kategorileri formatla
    $formatted_categories = [];
    foreach ($categories as $category) {
        $formatted_category = [
            'id' => (int)$category['id'],
            'key' => $category['name'],
            'name' => $category['display_name'],
            'description' => $category['description'],
            'icon' => $category['icon_name'],
            'sort_order' => (int)$category['sort_order'],
            'is_active' => (bool)$category['is_active'],
            'created_at' => $category['created_at']
        ];
        
        // Story sayısını ekle (eğer isteniyorsa)
        if ($include_counts) {
            $formatted_category['story_count'] = (int)$category['story_count'];
        }
        
        $formatted_categories[] = $formatted_category;
    }
    
    // Response data
    $response_data = [
        'categories' => $formatted_categories,
        'total' => count($formatted_categories)
    ];
    
    sendResponse(true, $response_data, 'Kategoriler başarıyla alındı');
    
} catch (PDOException $e) {
    error_log('Database Error: ' . $e->getMessage());
    sendError('Veritabanı hatası oluştu', 500);
} catch (Exception $e) {
    error_log('General Error: ' . $e->getMessage());
    sendError('Sunucu hatası oluştu', 500);
}
?>
