<?php
// api/news.php

declare(strict_types=1);

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

try {
    rvu_ensure_news_tables($pdo);
    $user = rvu_news_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    $path = trim((string)($_SERVER['PATH_INFO'] ?? ''), '/');
    $newsId = ctype_digit($path) ? (int)$path : null;

    if ($method === 'GET' && $newsId !== null) {
        $article = rvu_news_fetch_article($pdo, $newsId, (int)$user['id']);
        if (!$article) rvu_news_json(['detail' => 'News article not found.'], 404);
        if ($article['status'] === 'draft' && !rvu_news_can_manage($user, (int)$article['author_id'])) {
            rvu_news_json(['detail' => 'You do not have access to this draft.'], 403);
        }
        rvu_news_json($article);
    }

    if ($method === 'GET') {
        $status = strtolower(trim((string)($_GET['status'] ?? 'published')));
        if (!in_array($status, ['published', 'draft'], true)) $status = 'published';

        $mine = isset($_GET['mine']) && in_array(strtolower((string)$_GET['mine']), ['1', 'true', 'yes'], true);
        $campus = trim((string)($_GET['campus'] ?? ''));
        $category = trim((string)($_GET['category'] ?? ''));
        $query = trim((string)($_GET['q'] ?? ''));
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = min(50, max(1, (int)($_GET['limit'] ?? 10)));
        $offset = ($page - 1) * $limit;

        $where = ['n.status = ?'];
        $params = [$status];

        if ($status === 'draft' && !rvu_news_role_is_admin($user['role'] ?? '')) {
            $where[] = 'n.author_id = ?';
            $params[] = (int)$user['id'];
        } elseif ($mine) {
            $where[] = 'n.author_id = ?';
            $params[] = (int)$user['id'];
        }
        if ($campus !== '') {
            $where[] = 'n.campus = ?';
            $params[] = $campus;
        }
        if ($category !== '') {
            $where[] = 'n.category = ?';
            $params[] = $category;
        }
        if ($query !== '') {
            $where[] = '(n.title ILIKE ? OR n.body ILIKE ? OR u.full_name ILIKE ?)';
            $like = '%' . $query . '%';
            $params[] = $like;
            $params[] = $like;
            $params[] = $like;
        }

        $whereSql = implode(' AND ', $where);
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM campus_news n INNER JOIN users u ON u.id = n.author_id WHERE {$whereSql}");
        $countStmt->execute($params);
        $total = (int)$countStmt->fetchColumn();

        $sql = "SELECT
            n.id, n.author_id, n.title, n.body, n.category, n.campus, n.school, n.department,
            n.status, n.is_trending, n.created_at, n.updated_at, n.published_at,
            u.full_name AS author_name,
            u.role AS author_role,
            u.profile_picture AS author_profile_picture,
            (SELECT COUNT(*) FROM campus_news_likes l WHERE l.news_id = n.id) AS like_count,
            (SELECT COUNT(*) FROM campus_news_comments c WHERE c.news_id = n.id) AS comment_count,
            EXISTS(SELECT 1 FROM campus_news_likes ml WHERE ml.news_id = n.id AND ml.user_id = ?) AS liked_by_me,
            COALESCE((
                SELECT json_agg(
                    json_build_object(
                        'id', i.id,
                        'path', i.image_path,
                        'thumbnail_path', COALESCE(i.thumbnail_path, '')
                    ) ORDER BY i.position, i.id
                )
                FROM campus_news_images i WHERE i.news_id = n.id
            ), '[]'::json) AS images,
            (
                SELECT json_build_object(
                    'id', v.id,
                    'path', v.video_path,
                    'file_name', v.original_name,
                    'mime_type', v.mime_type,
                    'size_bytes', v.size_bytes,
                    'created_at', v.created_at
                )
                FROM campus_news_videos v
                WHERE v.news_id = n.id
                LIMIT 1
            ) AS video
          FROM campus_news n
          INNER JOIN users u ON u.id = n.author_id
          WHERE {$whereSql}
          ORDER BY COALESCE(n.published_at, n.created_at) DESC, n.id DESC
          LIMIT ? OFFSET ?";

        $listParams = array_merge([(int)$user['id']], $params, [$limit, $offset]);
        $stmt = $pdo->prepare($sql);
        $stmt->execute($listParams);
        $rows = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $rows[] = rvu_news_normalize_row($row);
        }

        rvu_news_json([
            'data' => $rows,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'has_more' => ($offset + count($rows)) < $total,
            ],
        ]);
    }

    if ($method === 'POST') {
        $input = rvu_news_input();
        $title = trim((string)($input['title'] ?? ''));
        $body = trim((string)($input['body'] ?? ''));
        $category = trim((string)($input['category'] ?? 'General'));
        $status = strtolower(trim((string)($input['status'] ?? 'published')));
        $isTrending = rvu_news_bool($input['is_trending'] ?? false);

        if (mb_strlen($title) < 4 || mb_strlen($title) > 180) {
            rvu_news_json(['detail' => 'News title must be between 4 and 180 characters.'], 422);
        }
        if (mb_strlen($body) < 10 || mb_strlen($body) > 20000) {
            rvu_news_json(['detail' => 'News story must be between 10 and 20,000 characters.'], 422);
        }
        if (!in_array($status, ['published', 'draft'], true)) $status = 'published';

        $campus = trim((string)($user['campus'] ?? '')) ?: 'University Wide';
        $school = trim((string)($user['school'] ?? '')) ?: null;
        $department = trim((string)($user['program'] ?? $user['department'] ?? '')) ?: null;

        $stmt = $pdo->prepare("INSERT INTO campus_news
            (author_id, title, body, category, campus, school, department, status, is_trending, published_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CASE WHEN ? = 'published' THEN CURRENT_TIMESTAMP ELSE NULL END)
            RETURNING id");
        // PDO_PGSQL can encode PHP false as an empty string when execute()
        // receives an untyped value. PostgreSQL rejects that for BOOLEAN.
        $stmt->execute([(int)$user['id'], $title, $body, $category, $campus, $school, $department, $status, $isTrending ? 'true' : 'false', $status]);
        $newId = (int)$stmt->fetchColumn();
        rvu_news_notify_trending($pdo, $newId, (int)$user['id']);
        rvu_news_json(['message' => $status === 'draft' ? 'Draft saved.' : 'News published.', 'id' => $newId], 201);
    }

    if ($method === 'PUT' && $newsId !== null) {
        $existing = rvu_news_fetch_article($pdo, $newsId, (int)$user['id']);
        if (!$existing) rvu_news_json(['detail' => 'News article not found.'], 404);
        if (!rvu_news_can_manage($user, (int)$existing['author_id'])) {
            rvu_news_json(['detail' => 'You can only edit your own news articles.'], 403);
        }

        $input = rvu_news_input();
        $fields = [];
        $params = [];
        if (array_key_exists('title', $input)) {
            $title = trim((string)$input['title']);
            if (mb_strlen($title) < 4 || mb_strlen($title) > 180) rvu_news_json(['detail' => 'News title must be between 4 and 180 characters.'], 422);
            $fields[] = 'title = ?';
            $params[] = $title;
        }
        if (array_key_exists('body', $input)) {
            $body = trim((string)$input['body']);
            if (mb_strlen($body) < 10 || mb_strlen($body) > 20000) rvu_news_json(['detail' => 'News story must be between 10 and 20,000 characters.'], 422);
            $fields[] = 'body = ?';
            $params[] = $body;
        }
        if (array_key_exists('category', $input)) {
            $category = trim((string)$input['category']);
            if ($category === '' || mb_strlen($category) > 60) rvu_news_json(['detail' => 'Invalid news category.'], 422);
            $fields[] = 'category = ?';
            $params[] = $category;
        }
        if (array_key_exists('is_trending', $input)) {
            $fields[] = 'is_trending = ?';
            // Bind PostgreSQL boolean literals as strings; false must not
            // become an empty PDO parameter.
            $params[] = rvu_news_bool($input['is_trending']) ? 'true' : 'false';
        }
        if (array_key_exists('status', $input)) {
            $status = strtolower(trim((string)$input['status']));
            if (!in_array($status, ['published', 'draft'], true)) rvu_news_json(['detail' => 'Invalid news status.'], 422);
            $fields[] = 'status = ?';
            $params[] = $status;
            $fields[] = $status === 'published'
                ? 'published_at = COALESCE(published_at, CURRENT_TIMESTAMP)'
                : 'published_at = NULL';
        }
        if (!$fields) rvu_news_json(['message' => 'Nothing to update.']);
        $fields[] = 'updated_at = CURRENT_TIMESTAMP';
        $params[] = $newsId;
        $stmt = $pdo->prepare('UPDATE campus_news SET ' . implode(', ', $fields) . ' WHERE id = ?');
        $stmt->execute($params);
        rvu_news_notify_trending($pdo, $newsId, (int)$user['id']);
        rvu_news_json(['message' => 'News article updated successfully.']);
    }

    if ($method === 'DELETE' && $newsId !== null) {
        $existing = rvu_news_fetch_article($pdo, $newsId, (int)$user['id']);
        if (!$existing) rvu_news_json(['detail' => 'News article not found.'], 404);
        if (!rvu_news_can_manage($user, (int)$existing['author_id'])) {
            rvu_news_json(['detail' => 'You can only delete your own news articles.'], 403);
        }

        $imgStmt = $pdo->prepare('SELECT image_path, thumbnail_path FROM campus_news_images WHERE news_id = ?');
        $imgStmt->execute([$newsId]);
        $images = $imgStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $videoStmt = $pdo->prepare('SELECT video_path FROM campus_news_videos WHERE news_id = ?');
        $videoStmt->execute([$newsId]);
        $videoPath = $videoStmt->fetchColumn();

        $pdo->prepare('DELETE FROM campus_news WHERE id = ?')->execute([$newsId]);

        foreach ($images as $row) {
            rvu_news_delete_media_file((string)$row['image_path']);
            if (!empty($row['thumbnail_path'])) rvu_news_delete_media_file((string)$row['thumbnail_path']);
        }
        if ($videoPath) rvu_news_delete_media_file((string)$videoPath);

        rvu_news_json(['message' => 'News article deleted.']);
    }

    rvu_news_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_news_json(['detail' => 'Campus News server error: ' . $e->getMessage()], 500);
}
