<?php

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ----------------------
// AUTH CHECK
// ----------------------
if (
    empty($_SESSION['admin_logged_in']) ||
    $_SESSION['admin_logged_in'] !== true
) {
    header('Location: /admin/login.php');
    exit;
}

$adminId = (int)($_SESSION['admin_user_id'] ?? 0);

if (!$adminId) {
    header('Location: /admin/login.php');
    exit;
}

// ----------------------
// POST ONLY
// ----------------------
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: /admin/messages');
    exit;
}

$box = $_POST['box'] ?? 'inbox';
$bulkAction = $_POST['bulk_action'] ?? '';
$messageIds = $_POST['message_ids'] ?? [];

$allowedBoxes = ['inbox', 'outbox'];
$allowedActions = ['mark_read', 'delete'];

if (!in_array($box, $allowedBoxes, true)) {
    header('Location: /admin/messages?bulk=invalid');
    exit;
}

if (!in_array($bulkAction, $allowedActions, true)) {
    header('Location: /admin/messages?bulk=invalid');
    exit;
}

if ($box === 'outbox' && $bulkAction === 'mark_read') {
    header('Location: /admin/messages?bulk=invalid');
    exit;
}

if (empty($messageIds) || !is_array($messageIds)) {
    header('Location: /admin/messages?bulk=none');
    exit;
}

$messageIds = array_values(array_unique(array_filter($messageIds, function ($id) {
    return ctype_digit((string)$id);
})));

if (empty($messageIds)) {
    header('Location: /admin/messages?bulk=none');
    exit;
}

$messageIds = array_map('intval', $messageIds);

$placeholders = implode(',', array_fill(0, count($messageIds), '?'));

try {
    if ($bulkAction === 'mark_read') {
        $params = array_merge([1], $messageIds, [$adminId]);

        $stmt = $pdo->prepare("
            UPDATE messages
            SET is_read = ?
            WHERE id IN ($placeholders)
              AND recipient_id = ?
        ");

        $stmt->execute($params);

        header('Location: /admin/messages?bulk=read');
        exit;
    }

    if ($bulkAction === 'delete') {
        if ($box === 'inbox') {
            $ownerColumn = 'recipient_id';
        } else {
            $ownerColumn = 'sender_id';
        }

        $params = array_merge($messageIds, [$adminId]);

        $stmt = $pdo->prepare("
            DELETE FROM messages
            WHERE id IN ($placeholders)
              AND $ownerColumn = ?
        ");

        $stmt->execute($params);

        header('Location: /admin/messages?bulk=deleted');
        exit;
    }

    header('Location: /admin/messages?bulk=invalid');
    exit;

} catch (Exception $e) {
    header('Location: /admin/messages?bulk=invalid');
    exit;
}