<?php
// messages.php - full page with working mark/unmark/delete handling

// Start session if not started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Load DB connection (adjust path if needed)
require __DIR__ . '/../config.php'; // <-- change if config.php sits elsewhere

// Determine current user id (adjust if your session var name differs)
$user_id = $_SESSION['SESS_USERID'] ?? $_SESSION['user_id'] ?? null;

// If no user, optionally redirect to login (uncomment if needed)
// if (!$user_id) { header("Location: login.php"); exit; }

// ---------- Handle POST actions BEFORE including header.php / sending output ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;

    try {
        if ($action === 'mark' && $id && $user_id) {
            $stmt = $pdo->prepare("UPDATE message SET marked = 1 WHERE id = ? AND log_id = ?");
            $stmt->execute([$id, $user_id]);
        } elseif ($action === 'unmark' && $id && $user_id) {
            $stmt = $pdo->prepare("UPDATE message SET marked = 0 WHERE id = ? AND log_id = ?");
            $stmt->execute([$id, $user_id]);
        } elseif ($action === 'delete' && $id && $user_id) {
            $stmt = $pdo->prepare("DELETE FROM message WHERE id = ? AND log_id = ?");
            $stmt->execute([$id, $user_id]);
        } elseif ($action === 'markAll' && $user_id) {
            $stmt = $pdo->prepare("UPDATE message SET marked = 1 WHERE marked = 0 AND status = 1 AND log_id = ?");
            $stmt->execute([$user_id]);
        } elseif ($action === 'unmarkAll' && $user_id) {
            $stmt = $pdo->prepare("UPDATE message SET marked = 0 WHERE marked = 1 AND status = 1 AND log_id = ?");
            $stmt->execute([$user_id]);
        }
    } catch (PDOException $e) {
        // optional: log error
        error_log("Message action error: " . $e->getMessage());
    }

    // Redirect back to the same page (clean URL) after POST - no output has been sent yet
    header("Location: " . basename(__FILE__));
    exit;
}

// Now include header (this outputs HTML head / nav / loads CSS & JS)
require "header.php";
?>

<main class="flex-1 px-2 py-2 md:p-4 pb-20 md:pb-6 overflow-hidden"
      wire:snapshot='{"data":{},"paginators":[{"page":1}],"memo":{"id":"555xKs59f7sLAnu9nchr","name":"user.notifications","path":"user/notifications","method":"GET"},"checksum":"321fa1ec2309"}'
      wire:effects='{"url":{"paginators.page":{"as":"page","use":"push"}}}'
      wire:id="555xKs59f7sLAnu9nchr"
      class="space-y-6">

    <!-- Page Title -->
    <div class="pb-4 border-b border-gray-800/50">
        <h1 class="text-2xl md:text-3xl font-bold text-white">
            📩 Notifications (OUTBOX)
        </h1>
        <p class="text-gray-400 text-sm mt-1">Manage your messages: read, unread, reply, or delete.</p>
    </div>

    <!-- Actions Row (use POST forms to trigger server actions) -->
    <div class="flex items-center justify-between">
        <div></div>
        <div class="flex items-center gap-3 pr-3 pt-3">
            <form method="post" style="display:inline">
                <input type="hidden" name="action" value="markAll">
                <button type="submit" class="flex items-center gap-2 px-4 py-2 bg-[#1A1428] text-[#2FE6DE] rounded-xl hover:bg-[#2A243B] transition-colors">
                    <i class="fas fa-check-circle" style="font-size: 1rem;"></i>
                    <span>Mark All as Read</span>
                </button>
            </form>

            <form method="post" style="display:inline">
                <input type="hidden" name="action" value="unmarkAll">
                <button type="submit" class="flex items-center gap-2 px-4 py-2 bg-[#1A1428] text-yellow-400 rounded-xl hover:bg-[#2A243B] transition-colors">
                    <i class="fas fa-undo" style="font-size: 1rem;"></i>
                    <span>Mark All as Unread</span>
                </button>
            </form>
        </div>
    </div>

    <div class="bg-[#0F0A1F] rounded-2xl p-6">
        <div class="space-y-4">

            <?php
            // Fetch messages: only status=2 and for this user
            $stmt = $pdo->prepare("SELECT * FROM message WHERE status = 1 AND log_id = ? ORDER BY date DESC");
            $stmt->execute([$user_id]);
            $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

            if (!$messages) {
                echo "<p class='text-gray-400'>No messages found.</p>";
            }

            foreach ($messages as $msg):
                $isUnread = ($msg['marked'] == 0);
            ?>

            <div class="bg-[#1A1428] rounded-xl p-4 hover:bg-[#2A243B] transition-colors relative overflow-hidden
                        border-l-4 <?= $isUnread ? 'border-[#2FE6DE]' : 'border-gray-600' ?>">

                <?php if ($isUnread): ?>
                    <div class="absolute top-4 right-4 w-2 h-2 rounded-full bg-[#2FE6DE]"></div>
                <?php endif; ?>

                <div class="flex items-start gap-4">
                    <div class="bg-[#2FE6DE]/10 p-3 rounded-xl flex-shrink-0">
                        <i class="fas fa-bell" style="font-size: 1.5rem; color: #2FE6DE;"></i>
                    </div>

                    <div class="flex-grow">
                        <div class="text-sm text-gray-400 mb-1">
                            <?= htmlspecialchars(date("M d, Y H:i", strtotime($msg['date']))) ?>
                        </div>

                        <p class="text-gray-100 font-semibold">
                            <?= htmlspecialchars($msg['title']) ?>
                        </p>

                        <p class="text-gray-300 text-sm">
                            <?= nl2br(htmlspecialchars($msg['note'])) ?>
                        </p>

                        <div class="text-xs text-gray-400 mt-2">
                            From: <?= htmlspecialchars($msg['name']) ?>
                            (<?= htmlspecialchars($msg['email']) ?>, <?= htmlspecialchars($msg['phone']) ?>)
                            | IP: <?= htmlspecialchars($msg['ip']) ?>
                        </div>

                        <div class="flex items-center gap-4 mt-3">
                            <!-- Mark or Unmark form -->
                            <?php if ($isUnread): ?>
                                <form method="post" style="display:inline">
                                    <input type="hidden" name="action" value="mark">
                                    <input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
                                    <button type="submit" class="text-sm text-[#2FE6DE] hover:text-[#20D6CE] transition-colors flex items-center gap-1">
                                        <i class="fas fa-check" style="font-size: 1rem;"></i> Mark as Read
                                    </button>
                                </form>
                            <?php else: ?>
                                <form method="post" style="display:inline">
                                    <input type="hidden" name="action" value="unmark">
                                    <input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
                                    <button type="submit" class="text-sm text-yellow-400 hover:text-yellow-300 transition-colors flex items-center gap-1">
                                        <i class="fas fa-undo" style="font-size: 1rem;"></i> Mark as Unread
                                    </button>
                                </form>
                            <?php endif; ?>

                            <!-- Reply (keeps as a link) -->
                            <a href="support.php?id=<?= (int)$msg['id'] ?>"
                               class="btn btn-primary flex items-center gap-1 text-sm transition-colors">
                                <i class="fas fa-reply" style="font-size: 1rem;"></i> Reply
                            </a>

                            <!-- Delete form (with JS confirm) -->
                            <form method="post" style="display:inline" onsubmit="return confirm('Are you sure you want to delete this message?')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= (int)$msg['id'] ?>">
                                <button type="submit" class="text-sm text-red-400 hover:text-red-300 transition-colors flex items-center gap-1">
                                    <i class="fas fa-trash" style="font-size: 1rem;"></i> Delete
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <?php endforeach; ?>

        </div>
    </div>
</main>

<?php require("footer.php"); ?>
