<?php
require_once __DIR__ . '/../core/response.php';
require_once __DIR__ . '/../core/db.php';

/**
 * =========================
 * PARSE ID FROM URL
 * =========================
 */
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = array_values(array_filter(explode('/', $uri)));
$idFromUrl = is_numeric(end($segments)) ? (int) end($segments) : null;

/**
 * =========================
 * SANITIZE GET
 * =========================
 */
$type = isset($_GET['type']) ? trim($_GET['type']) : null;
$lang = $_GET['lang'] ?? 'id';

$page  = isset($_GET['page']) ? max(1, (int) $_GET['page']) : 1;
$limit = isset($_GET['limit']) ? min(50, max(1, (int) $_GET['limit'])) : 8;
$offset = ($page - 1) * $limit;

$dateFrom = (
    isset($_GET['dateFrom']) &&
    preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['dateFrom'])
) ? $_GET['dateFrom'] : null;

$search = isset($_GET['search']) ? trim($_GET['search']) : null;

/**
 * =========================
 * BASE QUERY (DATA)
 * =========================
 */
$sql = "
    SELECT
        n.IDNews AS id,
        n.title,
        n.title_en,
        n.excerpt,
        n.excerpt_en,
        n.content,
        n.content_en,
        n.author,
        n.publish_date AS date,
        CASE
            WHEN a.FileName IS NOT NULL
            THEN CONCAT(a.Source, '/', a.FileName)
            ELSE NULL
        END AS imagePath
    FROM news n
    LEFT JOIN attachment a
        ON a.IDSource = n.IDNews
        AND a.Source = 'news'
        AND a.TipeMedia = 'image'
        AND a.Urutan = 1
    WHERE n.StatusNews = 'PUBLISHED'
";

/**
 * =========================
 * BASE QUERY (COUNT)
 * =========================
 */
$countSql = "
    SELECT COUNT(DISTINCT n.IDNews) AS total
    FROM news n
    WHERE n.StatusNews = 'PUBLISHED'
";

$params = [];
$countParams = [];

/**
 * =========================
 * MODE: DETAIL BY ID
 * =========================
 */
if ($idFromUrl && $type !== 'news') {

    $sql .= " AND n.IDNews = :id LIMIT 1";
    $params['id'] = $idFromUrl;

    $news = fetchOne($sql, $params);

    if (!$news) {
        jsonResponse(null, 404);
        exit;
    }

    $basePath = returnBasePath();

    if (!empty($news['imagePath'])) {
        $news['imagePath'] = $basePath . $news['imagePath'];
    }

    // lang fallback
    if ($lang === 'en') {
        if (!empty($news['title_en'])) {
            $news['title'] = $news['title_en'];
        }
        if (!empty($news['excerpt_en'])) {
            $news['excerpt'] = $news['excerpt_en'];
        }
        if (!empty($news['content_en'])) {
            $news['content'] = $news['content_en'];
        }
    }

    jsonResponse($news);
    exit;
}

/**
 * =========================
 * MODE: LIST WITH PAGINATION
 * =========================
 */
if ($type === 'news') {

    if ($dateFrom) {
        $sql      .= " AND n.publish_date >= :dateFrom";
        $countSql .= " AND n.publish_date >= :dateFrom";

        $params['dateFrom'] = $dateFrom;
        $countParams['dateFrom'] = $dateFrom;
    }

    if ($search !== '') {

        $sql .= "
            AND (
                n.title LIKE :search_title
                OR n.excerpt LIKE :search_excerpt
                OR n.title_en LIKE :search_title_en
                OR n.excerpt_en LIKE :search_excerpt_en
            )
        ";

        $countSql .= "
            AND (
                n.title LIKE :search_title
                OR n.excerpt LIKE :search_excerpt
                OR n.title_en LIKE :search_title_en
                OR n.excerpt_en LIKE :search_excerpt_en
            )
        ";

        $like = '%' . $search . '%';

        $params['search_title'] = $like;
        $params['search_excerpt'] = $like;
        $params['search_title_en'] = $like;
        $params['search_excerpt_en'] = $like;

        $countParams = $params;
    }

    $sql .= "
        ORDER BY n.publish_date DESC
        LIMIT $limit OFFSET $offset
    ";

    $news = fetchAll($sql, $params);
    $countRow = fetchOne($countSql, $countParams);

    $total = (int) ($countRow['total'] ?? 0);
    $totalPages = (int) ceil($total / $limit);

} else {

    /**
     * =========================
     * MODE: DEFAULT LIST
     * =========================
     */
    $sql .= "
        ORDER BY n.publish_date DESC
        LIMIT 10
    ";

    $news = fetchAll($sql, []);
}

/**
 * =========================
 * POST PROCESSING LIST
 * =========================
 */
$basePath = returnBasePath();

foreach ($news as &$item) {

    if (!empty($item['imagePath'])) {
        $item['imagePath'] = $basePath . $item['imagePath'];
    }

    if ($lang === 'en') {
        if (!empty($item['title_en'])) {
            $item['title'] = $item['title_en'];
        }
        if (!empty($item['excerpt_en'])) {
            $item['excerpt'] = $item['excerpt_en'];
        }
        if (!empty($item['content_en'])) {
            $item['content'] = $item['content_en'];
        }
    }
}
unset($item);

/**
 * =========================
 * RESPONSE
 * =========================
 */
if ($type === 'news') {

    jsonResponse([
        'data' => $news,
        'total' => $total,
        'page' => $page,
        'limit' => $limit,
        'totalPages' => $totalPages
    ]);

} else {

    jsonResponse($news);
}
