<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/* ================= INPUT ================= */
$page   = max(1, (int)($_GET['page'] ?? 1));
$limit  = 10;
$offset = ($page - 1) * $limit;

$search          = trim($_GET['search'] ?? '');
$status          = trim($_GET['status'] ?? '');
$approvalStatus  = trim($_GET['approval_status'] ?? '');

/* ================= WHERE ================= */
$where = [];
$params = [];

if ($search !== '') {
    $where[] = '(b.title LIKE :search OR b.excerpt LIKE :search)';
    $params['search'] = "%{$search}%";
}

if ($status !== '') {
    $where[] = 'b.status = :status';
    $params['status'] = $status;
}

if ($approvalStatus !== '') {
    $where[] = 'b.approval_status = :approval_status';
    $params['approval_status'] = $approvalStatus;
}

$whereSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

/* ================= COUNT ================= */
$countStmt = $db->prepare("
    SELECT COUNT(*)
    FROM blogs b
    {$whereSql}
");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$pages = max(1, (int)ceil($total / $limit));

/* ================= LIST ================= */
$listStmt = $db->prepare("
    SELECT
        b.id,
        b.title,
        b.slug,
        b.featured_image,
        b.status,
        b.approval_status,
        b.published_at,
        b.created_at,
        b.rejection_reason,
        e.name AS author_name
    FROM blogs b
    LEFT JOIN employees e ON e.id = b.created_by
    {$whereSql}
    ORDER BY b.created_at DESC
    LIMIT {$limit} OFFSET {$offset}
");
$listStmt->execute($params);
$blogs = $listStmt->fetchAll();

/* ================= RESPONSE ================= */
Response::success('Blogs fetched successfully', [
    'blogs' => $blogs,
    'pagination' => [
        'page'  => $page,
        'pages' => $pages,
        'total' => $total
    ]
]);
