<?php
// backend/api/get-announcement.php  — called by user dashboard
// backend/api/admin-get-announcements.php  — called by admin panel
// This single file handles both (admin gets all, user gets only active)
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

// ── DB Config ──────────────────────────────────────────────
$db_host = 'localhost';
$db_user = 'redhash_leoexx';       // ← your DB username
$db_pass = '$?P;XUSaG6u%m+3h';           // ← your DB password
$db_name = 'redhash_leoexx';

register_shutdown_function(function() {
    $err = error_get_last();
    if ($err && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR])) {
        if (!headers_sent()) header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => $err['message'], 'announcements' => []]);
    }
});

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
    echo json_encode(['status' => 'error', 'message' => 'DB failed', 'announcements' => []]);
    exit;
}
$conn->set_charset('utf8mb4');

// Auto-create table if missing
$conn->query("CREATE TABLE IF NOT EXISTS `announcements` (
    `id`         INT(11)      NOT NULL AUTO_INCREMENT,
    `title`      VARCHAR(200) NOT NULL,
    `message`    TEXT         NOT NULL,
    `image_path` VARCHAR(300) DEFAULT NULL,
    `active`     TINYINT(1)   NOT NULL DEFAULT 1,
    `created_at` DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

// Admin view (all) vs User view (active only)
$isAdmin = isset($_GET['admin']) && $_GET['admin'] === '1';
$where   = $isAdmin ? '' : 'WHERE active = 1';
$order   = 'ORDER BY created_at DESC';
$limit   = $isAdmin ? 'LIMIT 100' : 'LIMIT 1'; // user only gets latest active popup

$result = $conn->query(
    "SELECT id, title, message, image_path, active,
            DATE_FORMAT(created_at, '%d %b %Y') AS created_at
     FROM announcements $where $order $limit"
);

$announcements = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $announcements[] = $row;
    }
}

echo json_encode(['status' => 'success', 'announcements' => $announcements]);
$conn->close();