<?php
/**
 * Story Kartları API Endpoint
 * Namaz Vakitleri Admin Panel
 * Mobil uygulama için story kartları servisi
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, 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
    $category = isset($_GET['category']) ? trim($_GET['category']) : '';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 50;
    $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;
    $active_only = isset($_GET['active_only']) ? (bool)$_GET['active_only'] : true;
    
    // Limit kontrolü
    if ($limit > 100) {
        $limit = 100;
    }
    
    // WHERE koşullarını oluştur
    $where_conditions = [];
    $params = [];
    
    if ($active_only) {
        $where_conditions[] = "st.is_active = 1";
        $where_conditions[] = "sc.is_active = 1";
    }
    
    if (!empty($category)) {
        $where_conditions[] = "sc.name = ?";
        $params[] = $category;
    }
    
    $where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';
    
    // Toplam kayıt sayısını al
    $count_sql = "
        SELECT COUNT(*) as total 
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        $where_clause
    ";
    $stmt = $db->prepare($count_sql);
    $stmt->execute($params);
    $total_count = $stmt->fetch()['total'];
    
    // Story'leri al
    $sql = "
        SELECT 
            st.id,
            st.title,
            st.content,
            st.content_type,
            st.image_path,
            st.background_color,
            st.text_color,
            st.font_size,
            st.view_count,
            st.sort_order,
            st.created_at,
            st.updated_at,
            sc.name as category_key,
            sc.display_name as category_name,
            sc.icon_name as category_icon
        FROM story_cards st 
        JOIN story_categories sc ON st.category_id = sc.id 
        $where_clause
        ORDER BY st.sort_order ASC, st.created_at DESC 
        LIMIT $limit OFFSET $offset
    ";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $stories = $stmt->fetchAll();
    
    // Story'leri formatla
    $formatted_stories = [];
    foreach ($stories as $story) {
        $formatted_story = [
            'id' => (int)$story['id'],
            'title' => $story['title'],
            'content' => $story['content'],
            'content_type' => $story['content_type'],
            'background_color' => $story['background_color'],
            'text_color' => $story['text_color'],
            'font_size' => (int)$story['font_size'],
            'view_count' => (int)$story['view_count'],
            'sort_order' => (int)$story['sort_order'],
            'created_at' => $story['created_at'],
            'updated_at' => $story['updated_at'],
            'category' => [
                'key' => $story['category_key'],
                'name' => $story['category_name'],
                'icon' => $story['category_icon']
            ]
        ];
        
        // Görsel URL'si ekle
        if ($story['content_type'] === 'image' && !empty($story['image_path'])) {
            // Protokol belirleme
            $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? 'https' : 'http';
            
            // Host ve port
            $host = $_SERVER['HTTP_HOST'];
            
            // Mevcut script yolunu al ve uploads klasörüne yönlendir
            $script_dir = dirname($_SERVER['SCRIPT_NAME']); // /php/api
            $uploads_path = dirname($script_dir) . '/uploads/'; // /php/uploads/
            
            // Base URL oluştur
            $base_url = $protocol . '://' . $host . $uploads_path;
            
            $formatted_story['image_url'] = $base_url . $story['image_path'];
        } else {
            $formatted_story['image_url'] = null;
        }
        
        $formatted_stories[] = $formatted_story;
    }
    
    // Response data
    $response_data = [
        'stories' => $formatted_stories,
        'pagination' => [
            'total' => (int)$total_count,
            'limit' => $limit,
            'offset' => $offset,
            'has_more' => ($offset + $limit) < $total_count
        ]
    ];
    
    sendResponse(true, $response_data, 'Story kartları 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);
}
?>
