<?php
/* ============================================================================
   ADMIN — CONTACT MESSAGES INBOX
   ----------------------------------------------------------------------------
   Every message sent from the "Contact / যোগাযোগ করুন" form on the landing
   page (contact-process.php  ->  contact_messages) shows up here.

   status : 0 = unread   1 = read   2 = replied   3 = archived
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';

if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }

/* Only a staff account that was given this module may open the page */
require_once __DIR__ . '/../includes/rbac.php';
rbac_guard('manage_users');

$lang         = new Language($db);
$current_lang = $lang->getCurrentLanguage();

/* --------------------------------------------------------------------------
   Safety net — create / upgrade the table if the live DB does not have it yet
   (the same work is done by neosspmigration.php)
   -------------------------------------------------------------------------- */
try {
    $conn = $db->getConnection();
    $conn->query("CREATE TABLE IF NOT EXISTS contact_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100) NOT NULL,
        mobile VARCHAR(15) NOT NULL,
        service VARCHAR(100) NULL,
        message TEXT NULL,
        status TINYINT(1) NOT NULL DEFAULT 0,
        admin_note TEXT NULL,
        handled_by INT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT NULL,
        KEY idx_cm_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $has = function ($col) use ($conn) {
        try { $r = $conn->query("SHOW COLUMNS FROM `contact_messages` LIKE '$col'"); return $r && $r->num_rows > 0; }
        catch (\Throwable $e) { return true; }
    };
    if (!$has('admin_note')) { $conn->query("ALTER TABLE contact_messages ADD COLUMN admin_note TEXT NULL AFTER status"); }
    if (!$has('handled_by')) { $conn->query("ALTER TABLE contact_messages ADD COLUMN handled_by INT NULL AFTER admin_note"); }
    if (!$has('updated_at')) { $conn->query("ALTER TABLE contact_messages ADD COLUMN updated_at TIMESTAMP NULL DEFAULT NULL"); }
} catch (\Throwable $e) {}

$flash = $_SESSION['flash_success'] ?? '';
unset($_SESSION['flash_success']);

/* --------------------------------------------------------------------------
   Actions
   -------------------------------------------------------------------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    /* mark a single message read / replied / archived / unread + save note */
    if (isset($_POST['set_status'])) {
        $mid  = (int)($_POST['message_id'] ?? 0);
        $map  = ['unread' => 0, 'read' => 1, 'replied' => 2, 'archived' => 3];
        $st   = $map[$_POST['set_status']] ?? 1;
        $note = sanitize($_POST['admin_note'] ?? '');
        $db->insert("UPDATE contact_messages SET status = ?, admin_note = ?, handled_by = ?, updated_at = NOW() WHERE id = ?",
                    [$st, $note, (int)$_SESSION['user_id'], $mid]);
        $_SESSION['flash_success'] = 'Message updated.';
        redirect('messages.php' . (isset($_POST['back']) ? '?status=' . urlencode($_POST['back']) : ''));
    }

    /* delete */
    if (isset($_POST['delete_message'])) {
        $db->insert("DELETE FROM contact_messages WHERE id = ?", [(int)$_POST['message_id']]);
        $_SESSION['flash_success'] = 'Message deleted.';
        redirect('messages.php');
    }

    /* mark every unread message as read */
    if (isset($_POST['mark_all_read'])) {
        $db->insert("UPDATE contact_messages SET status = 1, updated_at = NOW() WHERE status = 0");
        $_SESSION['flash_success'] = 'All messages marked as read.';
        redirect('messages.php');
    }
}

/* --------------------------------------------------------------------------
   List + counters
   -------------------------------------------------------------------------- */
$STATUS = [
    0 => ['Unread',   'bg-amber-50 text-amber-700 border-amber-200',     'fa-envelope'],
    1 => ['Read',     'bg-slate-100 text-slate-600 border-slate-200',    'fa-envelope-open'],
    2 => ['Replied',  'bg-emerald-50 text-emerald-700 border-emerald-200','fa-reply'],
    3 => ['Archived', 'bg-slate-100 text-slate-500 border-slate-200',    'fa-box-archive'],
];

$f      = isset($_GET['status']) ? strtolower(trim($_GET['status'])) : 'unread';
$keymap = ['unread' => 0, 'read' => 1, 'replied' => 2, 'archived' => 3];
$q      = trim($_GET['q'] ?? '');

$where = []; $params = [];
if (isset($keymap[$f]))       { $where[] = "status = ?";                              $params[] = $keymap[$f]; }
if ($q !== '')                { $where[] = "(name LIKE ? OR mobile LIKE ? OR message LIKE ?)";
                                $params[] = "%$q%"; $params[] = "%$q%"; $params[] = "%$q%"; }
$wsql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$messages = $db->select("SELECT * FROM contact_messages $wsql ORDER BY id DESC LIMIT 300", $params);

$counts = [0 => 0, 1 => 0, 2 => 0, 3 => 0];
foreach ($db->select("SELECT status, COUNT(id) AS c FROM contact_messages GROUP BY status") as $r) {
    $counts[(int)$r['status']] = (int)$r['c'];
}
$total = array_sum($counts);

$raw_logo     = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$wa_country   = '91';
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Messages - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family:'Inter',sans-serif; } [x-cloak]{display:none!important;} </style>
</head>
<body class="bg-slate-100" x-data="{ open: null, sidebarOpen: window.innerWidth >= 768 }">

<div class="flex h-screen overflow-hidden">

    <?php include __DIR__ . '/includes/sidebar.php'; ?>

    <div class="flex-1 flex flex-col min-w-0 bg-gray-100 overflow-hidden">

        <header class="h-20 bg-white text-slate-800 flex items-center justify-between px-4 lg:px-8 shadow-sm border-b border-gray-200 z-40 relative flex-shrink-0">
            <div class="flex items-center min-w-0">
                <button @click="sidebarOpen = !sidebarOpen" class="p-2 mr-3 text-slate-500 hover:text-emerald-600 rounded-lg hover:bg-gray-100 transition-colors"><i class="fas fa-bars text-xl"></i></button>
                <div class="min-w-0">
                    <p class="font-extrabold leading-tight truncate">Messages</p>
                    <p class="text-[11px] text-slate-400">Enquiries sent from the website contact form</p>
                </div>
            </div>
            <?php if ($counts[0] > 0): ?>
            <form method="POST">
                <button type="submit" name="mark_all_read" value="1"
                        class="px-4 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold whitespace-nowrap">
                    <i class="fas fa-check-double mr-1"></i> Mark all read
                </button>
            </form>
            <?php endif; ?>
        </header>

        <main class="flex-1 overflow-y-auto px-4 lg:px-8 py-6">

            <?php if ($flash): ?>
            <div class="mb-5 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl text-sm font-medium">
                <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($flash); ?>
            </div>
            <?php endif; ?>

            <!-- counters -->
            <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5">
                <?php
                $tiles = [
                    ['Unread',   $counts[0], 'fa-envelope',      'from-amber-400 to-orange-500'],
                    ['Read',     $counts[1], 'fa-envelope-open', 'from-sky-400 to-blue-500'],
                    ['Replied',  $counts[2], 'fa-reply',         'from-emerald-400 to-teal-500'],
                    ['Total',    $total,     'fa-inbox',         'from-slate-400 to-slate-600'],
                ];
                foreach ($tiles as $t): ?>
                <div class="bg-white rounded-2xl border border-slate-200 p-4 flex items-center gap-3">
                    <span class="w-11 h-11 rounded-xl grid place-items-center text-white bg-gradient-to-br <?php echo $t[3]; ?>">
                        <i class="fas <?php echo $t[2]; ?>"></i>
                    </span>
                    <div>
                        <p class="text-2xl font-extrabold text-slate-800 leading-none"><?php echo (int)$t[1]; ?></p>
                        <p class="text-[11px] font-bold text-slate-400 uppercase tracking-wide mt-1"><?php echo $t[0]; ?></p>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <!-- filters + search -->
            <div class="flex flex-wrap items-center gap-2 mb-5">
                <?php foreach (['unread' => 'Unread', 'read' => 'Read', 'replied' => 'Replied', 'archived' => 'Archived', 'all' => 'All'] as $k => $lbl):
                    $on  = ($f === $k);
                    $cnt = isset($keymap[$k]) ? $counts[$keymap[$k]] : $total;
                ?>
                    <a href="?status=<?php echo $k; ?>" class="px-4 py-2 rounded-xl text-sm font-bold <?php echo $on ? 'bg-slate-900 text-white' : 'bg-white text-slate-600 border border-slate-200 hover:bg-slate-50'; ?>">
                        <?php echo $lbl; ?> (<?php echo $cnt; ?>)
                    </a>
                <?php endforeach; ?>

                <form method="GET" class="ml-auto flex items-center gap-2">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($f); ?>">
                    <input type="text" name="q" value="<?php echo htmlspecialchars($q); ?>" placeholder="Search name / mobile / text"
                           class="px-4 py-2 rounded-xl border border-slate-200 text-sm w-56 focus:ring-2 focus:ring-emerald-500 outline-none">
                    <button class="px-4 py-2 rounded-xl bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-bold"><i class="fas fa-magnifying-glass"></i></button>
                </form>
            </div>

            <!-- list -->
            <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
                <?php if (empty($messages)): ?>
                    <p class="p-12 text-center text-slate-500 text-sm">
                        <i class="fas fa-inbox text-3xl mb-3 text-slate-300 block"></i>No messages in this list.
                    </p>
                <?php else: ?>
                <div class="divide-y divide-slate-100">
                    <?php foreach ($messages as $m):
                        $st  = (int)$m['status'];
                        $sd  = $STATUS[$st] ?? $STATUS[1];
                        $id  = (int)$m['id'];
                        $wa  = preg_replace('/\D/', '', $m['mobile']);
                        if (strlen($wa) === 10) { $wa = $wa_country . $wa; }
                    ?>
                    <div class="p-5 <?php echo $st === 0 ? 'bg-amber-50/40' : ''; ?>">
                        <div class="flex flex-wrap items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="font-extrabold text-slate-800">
                                    <?php echo htmlspecialchars($m['name']); ?>
                                    <?php if ($st === 0): ?><span class="ml-2 align-middle inline-block w-2 h-2 rounded-full bg-amber-500"></span><?php endif; ?>
                                </p>
                                <p class="text-xs text-slate-500 mt-1.5">
                                    <i class="fas fa-phone text-slate-400 mr-1"></i><?php echo htmlspecialchars($m['mobile']); ?>
                                    <?php if (!empty($m['service'])): ?> · <i class="fas fa-user-tag text-slate-400 mr-1"></i><?php echo htmlspecialchars($m['service']); ?><?php endif; ?>
                                    · <?php echo date('d M Y, h:i A', strtotime($m['created_at'])); ?>
                                </p>
                                <p class="text-sm text-slate-700 mt-2 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 whitespace-pre-line"><?php echo nl2br(htmlspecialchars($m['message'])); ?></p>
                                <?php if (!empty($m['admin_note'])): ?>
                                    <p class="text-xs text-slate-600 mt-2"><b>Note:</b> <?php echo htmlspecialchars($m['admin_note']); ?></p>
                                <?php endif; ?>
                            </div>

                            <div class="flex flex-col items-end gap-2">
                                <span class="px-3 py-1 rounded-full text-[11px] font-bold border <?php echo $sd[1]; ?>">
                                    <i class="fas <?php echo $sd[2]; ?> mr-1"></i><?php echo $sd[0]; ?>
                                </span>
                                <div class="flex items-center gap-2">
                                    <a href="tel:<?php echo htmlspecialchars($m['mobile']); ?>" class="w-8 h-8 rounded-lg bg-sky-50 text-sky-600 grid place-items-center" title="Call"><i class="fas fa-phone text-xs"></i></a>
                                    <a href="https://wa.me/<?php echo htmlspecialchars($wa); ?>" target="_blank" rel="noopener" class="w-8 h-8 rounded-lg bg-emerald-50 text-emerald-600 grid place-items-center" title="WhatsApp"><i class="fab fa-whatsapp"></i></a>
                                    <button type="button" @click="open = (open === <?php echo $id; ?> ? null : <?php echo $id; ?>)"
                                            class="text-xs font-bold text-slate-500 hover:text-slate-800"><i class="fas fa-pen mr-1"></i> Update</button>
                                </div>
                            </div>
                        </div>

                        <form method="POST" x-show="open === <?php echo $id; ?>" x-cloak class="mt-4 space-y-2">
                            <input type="hidden" name="message_id" value="<?php echo $id; ?>">
                            <input type="hidden" name="back" value="<?php echo htmlspecialchars($f); ?>">
                            <input type="text" name="admin_note" value="<?php echo htmlspecialchars($m['admin_note'] ?? '', ENT_QUOTES); ?>"
                                   placeholder="Internal note (optional)"
                                   class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm">
                            <div class="flex flex-wrap gap-2">
                                <button type="submit" name="set_status" value="read"     class="px-4 py-2.5 rounded-lg bg-slate-700 hover:bg-slate-800 text-white font-bold text-sm"><i class="fas fa-envelope-open mr-1"></i> Mark read</button>
                                <button type="submit" name="set_status" value="replied"  class="px-4 py-2.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-sm"><i class="fas fa-reply mr-1"></i> Mark replied</button>
                                <button type="submit" name="set_status" value="archived" class="px-4 py-2.5 rounded-lg bg-slate-200 hover:bg-slate-300 text-slate-700 font-bold text-sm"><i class="fas fa-box-archive mr-1"></i> Archive</button>
                                <button type="submit" name="set_status" value="unread"   class="px-4 py-2.5 rounded-lg bg-amber-100 hover:bg-amber-200 text-amber-800 font-bold text-sm"><i class="fas fa-envelope mr-1"></i> Unread</button>
                                <button type="submit" name="delete_message" value="1" onclick="return confirm('Delete this message permanently?');"
                                        class="px-4 py-2.5 rounded-lg bg-rose-600 hover:bg-rose-700 text-white font-bold text-sm ml-auto"><i class="fas fa-trash mr-1"></i> Delete</button>
                            </div>
                        </form>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

        </main>
    </div>
</div>
</body>
</html>
