<?php
// Include header (which includes all dependencies)
include 'includes/header.php';

// Make sure user is admin
if (!isLoggedIn() || !isAdmin()) {
    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_PERMISSION_DENIED'] ?? 'You do not have permission to manage news', 'danger');
    redirectTo('news');
    exit;
}

// Only process POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate CSRF token first
    if (!isset($_POST['csrf_token']) || !validate_csrf_token($_POST['csrf_token'])) {
        $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_ERROR_INVALID_CSRF'] ?? 'Invalid CSRF token. Please try again.', 'danger');
        redirectTo('news');
        exit;
    }

    // Get the action
    $action = isset($_POST['action']) ? sanitizeInput($_POST['action']) : '';

    try {
        // Handle add news
        if ($action === 'add') {
            $title = isset($_POST['title']) ? sanitizeInput($_POST['title']) : '';
            $message = isset($_POST['message']) ? cleanHTML($_POST['message']) : '';
            $category = isset($_POST['category']) ? sanitizeInput($_POST['category']) : '';
            $created_at = isset($_POST['created_at']) && !empty($_POST['created_at']) ? date('Y-m-d H:i:s', strtotime($_POST['created_at'])) : getCurrentDateTime();
            $currentDateTime = getCurrentDateTime();

            if (empty($title) || empty($message)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_NEWS_TITLE_MESSAGE_REQUIRED'] ?? 'Both title and message are required', 'danger');
            } else {
                $stmt = $pdo->prepare("INSERT INTO news (title, message, category, created_at, updated_at) VALUES (?, ?, ?, ?, ?)");
                if ($stmt->execute([$title, $message, $category, $created_at, $currentDateTime])) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_NEWS_ADDED_SUCCESS'] ?? 'News added successfully');
                } else {
                    $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_NEWS_ERROR_ADDING_PREFIX'] ?? 'Error adding news: ') . implode(' ', $stmt->errorInfo()), 'danger');
                }
            }
        }
        // Handle edit news
        elseif ($action === 'edit') {
            $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;
            $title = isset($_POST['title']) ? sanitizeInput($_POST['title']) : '';
            $message = isset($_POST['message']) ? cleanHTML($_POST['message']) : '';
            $category = isset($_POST['category']) ? sanitizeInput($_POST['category']) : '';
            $created_at = isset($_POST['created_at']) && !empty($_POST['created_at']) ? date('Y-m-d H:i:s', strtotime($_POST['created_at'])) : null;

            if (empty($title) || empty($message)) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_NEWS_TITLE_MESSAGE_REQUIRED'] ?? 'Both title and message are required', 'danger');
            } else {
                $currentDateTime = getCurrentDateTime();
                if ($created_at) {
                    $stmt = $pdo->prepare("UPDATE news SET title = ?, message = ?, category = ?, created_at = ?, updated_at = ? WHERE id = ?");
                    $result = $stmt->execute([$title, $message, $category, $created_at, $currentDateTime, $id]);
                } else {
                    $stmt = $pdo->prepare("UPDATE news SET title = ?, message = ?, category = ?, updated_at = ? WHERE id = ?");
                    $result = $stmt->execute([$title, $message, $category, $currentDateTime, $id]);
                }
                if ($result) {
                    $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_NEWS_UPDATED_SUCCESS'] ?? 'News updated successfully');
                } else {
                    $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_NEWS_ERROR_UPDATING_PREFIX'] ?? 'Error updating news: ') . implode(' ', $stmt->errorInfo()), 'danger');
                }
            }
        }
        // Handle delete news
        elseif ($action === 'delete') {
            $id = isset($_POST['id']) ? (int) $_POST['id'] : 0;

            $stmt = $pdo->prepare("DELETE FROM news WHERE id = ?");
            if ($stmt->execute([$id])) {
                $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_NEWS_DELETED_SUCCESS'] ?? 'News deleted successfully');
            } else {
                $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_NEWS_ERROR_DELETING_PREFIX'] ?? 'Error deleting news: ') . implode(' ', $stmt->errorInfo()), 'danger');
            }
        } else {
            $_SESSION['alert'] = displayAlert($lang_alerts['ALERT_INVALID_ACTION'] ?? 'Invalid action', 'danger');
        }
    } catch (PDOException $e) {
        $_SESSION['alert'] = displayAlert(($lang_alerts['ALERT_DATABASE_ERROR_PREFIX'] ?? 'Database error: ') . $e->getMessage(), 'danger');
    }
}

// Redirect back to the news page through the router
redirectTo('news');
exit;
?>