<?php
// backend/api/admin-save-announcement.php
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';

// Upload directory (relative to project root — must be web-accessible)
$uploadDir = '../../uploads/announcements/';

function jsonOut($status, $message, $extra = []) {
    echo json_encode(array_merge(['status' => $status, 'message' => $message], $extra));
    exit;
}

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' => 'Server error: ' . $err['message']]);
    }
});

if ($_SERVER['REQUEST_METHOD'] !== 'POST') jsonOut('error', 'Method not allowed.');

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) jsonOut('error', 'DB failed: ' . $conn->connect_error);
$conn->set_charset('utf8mb4');

// Auto-create table
$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");

$action = trim($_POST['action'] ?? '');
$id     = intval($_POST['id']   ?? 0);

// ── DELETE ─────────────────────────────────────────────────
if ($action === 'delete') {
    if (!$id) jsonOut('error', 'ID missing.');
    // Get image path to delete file
    $r = $conn->query("SELECT image_path FROM announcements WHERE id=$id");
    if ($r && $row = $r->fetch_assoc()) {
        if ($row['image_path']) {
            $fullPath = '../../' . $row['image_path'];
            if (file_exists($fullPath)) @unlink($fullPath);
        }
    }
    $conn->query("DELETE FROM announcements WHERE id=$id");
    jsonOut('success', 'Deleted.');
}

// ── TOGGLE STATUS ──────────────────────────────────────────
if ($id && !isset($_POST['title'])) {
    $active = intval($_POST['active'] ?? 0);
    $stmt   = $conn->prepare("UPDATE announcements SET active=? WHERE id=?");
    $stmt->bind_param('ii', $active, $id);
    $stmt->execute();
    jsonOut('success', 'Status updated.');
}

// ── CREATE NEW ─────────────────────────────────────────────
$title   = trim($_POST['title']   ?? '');
$message = trim($_POST['message'] ?? '');
$active  = intval($_POST['active'] ?? 1);

if (!$title || !$message) jsonOut('error', 'Title and message required.');

// Handle image upload
$imagePath = null;
if (!empty($_FILES['image']['name'])) {
    $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    $fileType = mime_content_type($_FILES['image']['tmp_name']);
    if (!in_array($fileType, $allowedTypes)) jsonOut('error', 'Invalid image type.');
    if ($_FILES['image']['size'] > 5 * 1024 * 1024) jsonOut('error', 'Image too large (max 5MB).');

    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    $ext      = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $filename = 'ann_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . strtolower($ext);
    $destPath = $uploadDir . $filename;

    if (!move_uploaded_file($_FILES['image']['tmp_name'], $destPath)) {
        jsonOut('error', 'Failed to save image. Check folder permissions.');
    }
    $imagePath = 'uploads/announcements/' . $filename;
}

$stmt = $conn->prepare(
    "INSERT INTO announcements (title, message, image_path, active, created_at) VALUES (?, ?, ?, ?, NOW())"
);
$stmt->bind_param('sssi', $title, $message, $imagePath, $active);

if ($stmt->execute()) {
    jsonOut('success', 'Announcement published.', ['id' => $stmt->insert_id]);
} else {
    jsonOut('error', 'DB insert failed: ' . $stmt->error);
}

$conn->close();