<?php
/**
 * Blogs API Endpoint
 * Fetches blogs from database with pagination and search
 */

require_once '../../includes/db_connection.php';
require_once '../includes/auth.php';

// Require authentication
requireAuth();

header('Content-Type: application/json');

// Handle DELETE requests
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    try {
        $db = Database::getInstance()->getConnection();
        $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        if ($id <= 0) {
            throw new Exception('Invalid blog ID');
        }
        
        $stmt = $db->prepare("DELETE FROM blogs WHERE id = ?");
        $stmt->execute([$id]);
        
        echo json_encode(['success' => true, 'message' => 'Blog deleted successfully']);
        exit;
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to delete blog']);
        exit;
    }
}

// Only allow GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $db = Database::getInstance()->getConnection();
    
    // Get parameters
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 9; // 9 cards per page looks good in grid
    $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    $category = isset($_GET['category']) ? trim($_GET['category']) : '';
    $offset = ($page - 1) * $limit;
    
    // Build query
    $where = [];
    $params = [];
    
    // Base query
    $baseQuery = "
        FROM blogs b
        LEFT JOIN admin_users u ON b.author_id = u.id
    ";
    
    if (!empty($search)) {
        $where[] = "(b.title LIKE ? OR b.excerpt LIKE ? OR b.content LIKE ?)";
        $searchTerm = "%{$search}%";
        $params[] = $searchTerm;
        $params[] = $searchTerm;
        $params[] = $searchTerm;
    }
    
    if (!empty($category)) {
        $where[] = "b.category = ?";
        $params[] = $category;
    }
    
    $whereClause = !empty($where) ? 'WHERE ' . implode(' AND ', $where) : '';
    
    // Get total count
    $countQuery = "SELECT COUNT(*) as total $baseQuery $whereClause";
    $stmt = $db->prepare($countQuery);
    $stmt->execute($params);
    $totalBlogs = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Get blogs
    $query = "
        SELECT 
            b.*,
            u.username as author_name,
            u.avatar as author_avatar
        $baseQuery
        $whereClause
        ORDER BY b.created_at DESC
        LIMIT ? OFFSET ?
    ";
    
    $params[] = $limit;
    $params[] = $offset;
    
    $stmt = $db->prepare($query);
    $stmt->execute($params);
    $blogs = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format blogs
    $formattedBlogs = [];
    foreach ($blogs as $blog) {
        $formattedBlogs[] = [
            'id' => $blog['id'],
            'title' => $blog['title'],
            'slug' => $blog['slug'],
            'excerpt' => $blog['excerpt'],
            'category' => $blog['category'],
            'featured_image' => $blog['featured_image'] ?: 'assets/images/extra/card/img-1.jpg',
            'author_name' => $blog['author_name'] ?: 'Admin',
            'author_avatar' => $blog['author_avatar'] ?: 'assets/images/users/avatar-1.jpg',
            'visibility' => $blog['visibility'],
            'published_at' => $blog['published_at'] ? date('d M Y', strtotime($blog['published_at'])) : 'Draft',
            'created_at' => date('d M Y', strtotime($blog['created_at']))
        ];
    }
    
    // Calculate pagination
    $totalPages = ceil($totalBlogs / $limit);
    
    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $formattedBlogs,
        'pagination' => [
            'current_page' => $page,
            'total_pages' => $totalPages,
            'total_blogs' => $totalBlogs,
            'per_page' => $limit,
            'has_next' => $page < $totalPages,
            'has_prev' => $page > 1
        ]
    ]);
    
} catch (Exception $e) {
    error_log('Blogs API error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch blogs'
    ]);
}
?>