<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . "/includes/db.php";

/**
 * -------------------------------------------------------------------------
 * AUTH
 * -------------------------------------------------------------------------
 */
if (!isset($_SESSION['admin_id'])) {
    if ($_SERVER['REQUEST_METHOD'] === "POST") {
        $u = trim($_POST['username'] ?? '');
        $p = hash("sha256", $_POST['password'] ?? '');

        $stmt = $conn->prepare("SELECT id FROM admins WHERE username = ? AND password = ?");
        $stmt->bind_param("ss", $u, $p);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($user = $result->fetch_assoc()) {
            $_SESSION['admin_id'] = (int)$user['id'];
            header("Location: dashboard.php");
            exit;
        } else {
            $error = "Invalid credentials.";
        }
    }

    // Simple inline login UI (keeps this dashboard self-contained)
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin Login</title>
        <script src="https://cdn.tailwindcss.com"></script>
    </head>
    <body class="min-h-screen flex items-center justify-center bg-slate-900">
        <form method="post" class="w-full max-w-md bg-white/5 border border-white/10 p-8 rounded-2xl shadow-2xl">
            <h1 class="text-2xl font-bold text-white mb-2">Admin Login</h1>
            <p class="text-slate-300 text-sm mb-6">Sign in to manage content.</p>

            <?php if (!empty($error)): ?>
                <div class="bg-red-500/10 border border-red-500/30 text-red-200 px-4 py-3 rounded-xl mb-4 text-sm">
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>

            <label class="block text-sm text-slate-200 mb-2">Username</label>
            <input name="username" required class="w-full mb-4 px-4 py-3 rounded-xl bg-white/10 border border-white/10 text-white outline-none focus:ring-2 focus:ring-blue-500">

            <label class="block text-sm text-slate-200 mb-2">Password</label>
            <input type="password" name="password" required class="w-full mb-6 px-4 py-3 rounded-xl bg-white/10 border border-white/10 text-white outline-none focus:ring-2 focus:ring-blue-500">

            <button class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 rounded-xl transition">
                Login
            </button>
        </form>
    </body>
    </html>
    <?php
    exit;
}

/**
 * -------------------------------------------------------------------------
 * HELPERS
 * -------------------------------------------------------------------------
 */
function admin_upload_file(string $inputName, string $uploadDirAbs, array $allowedExts): ?string
{
    if (!isset($_FILES[$inputName]) || !is_array($_FILES[$inputName])) return null;
    if (($_FILES[$inputName]['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return null;

    $name = $_FILES[$inputName]['name'] ?? '';
    $tmp  = $_FILES[$inputName]['tmp_name'] ?? '';

    if ($name === '' || $tmp === '') return null;

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExts, true)) return null;

    if (!is_dir($uploadDirAbs)) {
        mkdir($uploadDirAbs, 0755, true);
    }

    $safeBase = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', basename($name));
    $filename = time() . "_" . $safeBase;

    $fullPath = rtrim($uploadDirAbs, "/") . "/" . $filename;
    if (!move_uploaded_file($tmp, $fullPath)) return null;

    // Return DB/web path relative to admin folder
    return "uploads/" . $filename;
}

function admin_clean_url(?string $url): ?string
{
    $url = trim((string)$url);
    if ($url === '') return null;
    if (!filter_var($url, FILTER_VALIDATE_URL)) return null;
    return $url;
}

/**
 * -------------------------------------------------------------------------
 * ACTIONS
 * -------------------------------------------------------------------------
 */
$page = $_GET['page'] ?? 'users';
$page = preg_replace('/[^a-z_]/', '', $page); // basic whitelist-ish

// Article create
if (isset($_POST['save_article'])) {
    $title = trim($_POST['title'] ?? '');
    $body  = trim($_POST['body'] ?? '');

    if ($title !== '' && $body !== '') {
        $imgPath = admin_upload_file('image', __DIR__ . "/uploads", ['jpg', 'jpeg', 'png', 'webp', 'gif']);

        if ($imgPath) {
            $stmt = $conn->prepare("INSERT INTO articles (title, body, image) VALUES (?, ?, ?)");
            $stmt->bind_param("sss", $title, $body, $imgPath);
            $stmt->execute();
        }
    }

    header("Location: dashboard.php?page=articles");
    exit;
}

// Banner upload
if (isset($_POST['add_banner'])) {
    $imgPath = admin_upload_file('banner', __DIR__ . "/uploads", ['jpg', 'jpeg', 'png', 'webp', 'gif']);
    if ($imgPath) {
        $stmt = $conn->prepare("INSERT INTO banners (image) VALUES (?)");
        $stmt->bind_param("s", $imgPath);
        $stmt->execute();
    }
    header("Location: dashboard.php?page=banners");
    exit;
}

// Doctor reply
if (isset($_POST['send_reply'])) {
    $user_id = (int)($_POST['user_id'] ?? 0);
    $reply   = trim($_POST['reply'] ?? '');
    $doctor_id = 1;

    if ($user_id > 0 && $reply !== '') {
        $stmt = $conn->prepare("
            INSERT INTO doctor_messages
            (user_id, doctor_id, message, image, audio, sender, seen)
            VALUES (?, ?, ?, NULL, NULL, 'doctor', 0)
        ");
        $stmt->bind_param("iis", $user_id, $doctor_id, $reply);
        $stmt->execute();
    }

    header("Location: dashboard.php?page=chat&uid=" . $user_id);
    exit;
}

// Save food (pregnancy_foods)
if (isset($_POST['save_food'])) {
    $category = $_POST['category'] ?? 'pregnant';
    $trimester = $_POST['trimester'] ?? null;
    $title = trim($_POST['title'] ?? '');
    $content_type = $_POST['content_type'] ?? 'text';
    $food_name = trim($_POST['food_name'] ?? '');
    $benefits = trim($_POST['benefits'] ?? '');
    $caution = trim($_POST['caution'] ?? '');
    $video_url = null;

    $allowedCategories = ['baby', 'pregnant', 'breastfeeding'];
    $allowedTrimesters = ['1', '2', '3'];
    $allowedTypes = ['text', 'video'];

    if (!in_array($category, $allowedCategories, true)) $category = 'pregnant';
    if ($trimester !== null && $trimester !== '' && !in_array($trimester, $allowedTrimesters, true)) $trimester = null;
    if (!in_array($content_type, $allowedTypes, true)) $content_type = 'text';

    if ($title !== '' && $benefits !== '') {

        if ($content_type === 'video') {
            // 1) file upload (mp4/webm/mov)
            $uploaded = admin_upload_file('video_file', __DIR__ . "/uploads", ['mp4', 'webm', 'mov', 'm4v']);
            if ($uploaded) {
                $video_url = $uploaded;
            } else {
                // 2) direct URL / YouTube URL
                $video_url = admin_clean_url($_POST['video_url'] ?? null);
            }
        }

        $stmt = $conn->prepare("
            INSERT INTO pregnancy_foods
            (category, trimester, title, content_type, food_name, benefits, caution, video_url)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");
        $stmt->bind_param(
            "ssssssss",
            $category,
            $trimester,
            $title,
            $content_type,
            $food_name,
            $benefits,
            $caution,
            $video_url
        );
        $stmt->execute();
    }

    header("Location: dashboard.php?page=foods");
    exit;
}

// Delete food
if (isset($_GET['del_food'])) {
    $id = (int)$_GET['del_food'];
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM pregnancy_foods WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
    }
    header("Location: dashboard.php?page=foods");
    exit;
}

// Save avoid food (pregnancy_foods_avoid)
if (isset($_POST['save_avoid'])) {
    $category = $_POST['category'] ?? 'pregnant';
    $food_name = trim($_POST['food_name'] ?? '');
    $reason = trim($_POST['reason'] ?? '');

    $allowedCategories = ['baby', 'pregnant', 'breastfeeding'];
    if (!in_array($category, $allowedCategories, true)) $category = 'pregnant';

    if ($food_name !== '' && $reason !== '') {
        $stmt = $conn->prepare("
            INSERT INTO pregnancy_foods_avoid
            (category, food_name, reason)
            VALUES (?, ?, ?)
        ");
        $stmt->bind_param("sss", $category, $food_name, $reason);
        $stmt->execute();
    }

    header("Location: dashboard.php?page=foods&tab=avoid");
    exit;
}

// Delete avoid
if (isset($_GET['del_avoid'])) {
    $id = (int)$_GET['del_avoid'];
    if ($id > 0) {
        $stmt = $conn->prepare("DELETE FROM pregnancy_foods_avoid WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
    }
    header("Location: dashboard.php?page=foods&tab=avoid");
    exit;
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Dashboard | Mama's Care</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50 font-sans text-gray-900">

<div class="flex min-h-screen">
    <aside class="w-72 bg-slate-900 text-white flex flex-col">
        <div class="p-6 text-2xl font-bold tracking-wider border-b border-slate-800">
            <i class="fas fa-heart-pulse mr-2 text-pink-400"></i>MAMA ADMIN
        </div>

        <nav class="flex-1 p-4 space-y-2">
            <?php
            $nav = [
                'users'    => ['icon' => 'users', 'label' => 'User Management'],
                'articles' => ['icon' => 'newspaper', 'label' => 'Health Articles'],
                'banners'  => ['icon' => 'image', 'label' => 'Banners'],
                'foods'    => ['icon' => 'utensils', 'label' => 'Foods'],
                'chat'     => ['icon' => 'comments', 'label' => 'Doctor Chat'],
                'subs'     => ['icon' => 'credit-card', 'label' => 'Subscriptions'],
            ];
            foreach ($nav as $key => $item):
                $active = ($page === $key) ? 'bg-blue-600 text-white' : 'text-slate-400 hover:bg-slate-800 hover:text-white';
            ?>
            <a href="?page=<?= $key ?>" class="flex items-center p-3 rounded-lg transition-all <?= $active ?>">
                <i class="fas fa-<?= $item['icon'] ?> w-6"></i> <?= $item['label'] ?>
            </a>
            <?php endforeach; ?>
        </nav>

        <div class="p-4 border-t border-slate-800">
            <a href="logout.php" class="flex items-center p-3 text-red-400 hover:bg-red-900/20 rounded-lg">
                <i class="fas fa-sign-out-alt w-6"></i> Logout
            </a>
        </div>
    </aside>

    <main class="flex-1 p-10">
        <header class="mb-8">
            <h1 class="text-3xl font-bold capitalize"><?= htmlspecialchars(str_replace('_', ' ', $page)) ?></h1>
            <p class="text-gray-500">Manage your platform content here.</p>
        </header>

        <?php if($page === "users"): ?>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <table class="w-full text-left">
                    <thead class="bg-gray-50 border-b">
                        <tr>
                            <th class="p-4 font-semibold text-gray-600">ID</th>
                            <th class="p-4 font-semibold text-gray-600">Name</th>
                            <th class="p-4 font-semibold text-gray-600">Phone</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php $r = $conn->query("SELECT * FROM users ORDER BY id DESC"); ?>
                        <?php while($u = $r->fetch_assoc()): ?>
                        <tr class="hover:bg-gray-50">
                            <td class="p-4 text-gray-500">#<?= (int)$u['id'] ?></td>
                            <td class="p-4 font-medium"><?= htmlspecialchars($u['name'] ?? '') ?></td>
                            <td class="p-4 font-mono text-sm"><?= htmlspecialchars($u['phone'] ?? '') ?></td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

        <?php elseif($page === "articles"): ?>
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 h-fit">
                    <h3 class="text-lg font-bold mb-4 flex items-center">
                        <i class="fas fa-plus-circle mr-2 text-blue-500"></i> New Article
                    </h3>
                    <form method="post" enctype="multipart/form-data" class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                            <input name="title" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Enter article title..." required>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Content</label>
                            <textarea name="body" rows="6" class="w-full p-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Write health content here..." required></textarea>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">Cover Image</label>
                            <input type="file" name="image" accept="image/*"
                                class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100 border rounded-lg p-1" required>
                        </div>
                        <button name="save_article" class="w-full bg-blue-600 text-white py-2.5 rounded-lg font-bold hover:bg-blue-700 transition shadow-lg shadow-blue-200">
                            Publish Article
                        </button>
                    </form>
                </div>

                <div class="lg:col-span-2 space-y-4">
                    <h3 class="text-lg font-bold mb-4">Published Articles</h3>
                    <?php $res = $conn->query("SELECT * FROM articles ORDER BY id DESC"); ?>
                    <?php if($res->num_rows == 0): ?>
                        <p class="text-gray-400 italic">No articles published yet.</p>
                    <?php endif; ?>
                    <?php while($a = $res->fetch_assoc()): ?>
                        <div class="bg-white p-4 rounded-xl shadow-sm border border-gray-200 flex gap-4 hover:border-blue-300 transition">
                            <img src="<?= htmlspecialchars($a['image'] ?? '') ?>" class="w-32 h-24 object-cover rounded-lg bg-gray-100 shrink-0">
                            <div class="flex-1">
                                <h4 class="font-bold text-lg text-slate-800 leading-tight"><?= htmlspecialchars($a['title'] ?? '') ?></h4>
                                <p class="text-gray-500 text-sm line-clamp-2 mt-1"><?= htmlspecialchars($a['body'] ?? '') ?></p>
                                <div class="mt-2 text-[10px] font-bold uppercase tracking-wider text-blue-500">Active Article</div>
                            </div>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>

        <?php elseif($page === "banners"): ?>
            <div class="space-y-8">
                <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200">
                    <h3 class="text-lg font-bold mb-4 flex items-center text-slate-800">
                        <i class="fas fa-images mr-2 text-blue-500"></i> Mobile App Banners
                    </h3>
                    <form method="post" enctype="multipart/form-data" class="flex flex-col md:flex-row items-end gap-4 bg-gray-50 p-4 rounded-lg">
                        <div class="flex-1 w-full">
                            <label class="block text-sm font-medium text-gray-700 mb-1">Select Banner Image</label>
                            <input type="file" name="banner" accept="image/*" required
                                class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-600 file:text-white hover:file:bg-blue-700 border border-gray-300 bg-white rounded-lg p-1">
                        </div>
                        <button name="add_banner" class="bg-blue-600 text-white px-8 py-2.5 rounded-lg font-bold hover:bg-blue-700 transition h-[42px] shrink-0 shadow-lg shadow-blue-200">
                            Upload
                        </button>
                    </form>
                </div>

                <div>
                    <h3 class="text-lg font-bold mb-4 text-slate-800">Active Banners</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php $res = $conn->query("SELECT * FROM banners ORDER BY id DESC"); ?>
                        <?php while($b = $res->fetch_assoc()): ?>
                            <div class="bg-white rounded-xl overflow-hidden shadow-sm border border-gray-200">
                                <img src="<?= htmlspecialchars($b['image'] ?? '') ?>" class="w-full h-48 object-cover">
                                <div class="p-3 flex justify-between items-center bg-white border-t">
                                    <span class="text-xs text-gray-400 font-mono truncate">ID: #<?= (int)$b['id'] ?></span>
                                    <span class="text-[10px] bg-green-100 text-green-700 px-2 py-0.5 rounded-full font-bold uppercase">Live</span>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
            </div>

        <?php elseif($page === "foods"): ?>
            <?php $tab = $_GET['tab'] ?? 'eat'; $tab = ($tab === 'avoid') ? 'avoid' : 'eat'; ?>

            <div class="flex items-center justify-between mb-6">
                <div>
                    <h2 class="text-xl font-bold text-slate-800">Foods Module</h2>
                    <p class="text-sm text-gray-500">Add foods (text or video) and foods to avoid.</p>
                </div>

                <div class="inline-flex bg-white border rounded-xl p-1 shadow-sm">
                    <a href="?page=foods&tab=eat" class="px-4 py-2 rounded-lg text-sm font-bold <?= $tab==='eat' ? 'bg-blue-600 text-white' : 'text-gray-600 hover:bg-gray-50' ?>">
                        Foods
                    </a>
                    <a href="?page=foods&tab=avoid" class="px-4 py-2 rounded-lg text-sm font-bold <?= $tab==='avoid' ? 'bg-blue-600 text-white' : 'text-gray-600 hover:bg-gray-50' ?>">
                        Avoid
                    </a>
                </div>
            </div>

            <?php if ($tab === 'eat'): ?>
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 h-fit">
                        <h3 class="text-lg font-bold mb-4 flex items-center">
                            <i class="fas fa-utensils mr-2 text-blue-500"></i> Add Food
                        </h3>

                        <form method="post" enctype="multipart/form-data" class="space-y-4">
                            <div class="grid grid-cols-2 gap-3">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                                    <select name="category" class="w-full p-2 border rounded-lg">
                                        <option value="pregnant">Pregnant</option>
                                        <option value="breastfeeding">Breastfeeding</option>
                                        <option value="baby">Baby</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Trimester (optional)</label>
                                    <select name="trimester" class="w-full p-2 border rounded-lg">
                                        <option value="">All / N/A</option>
                                        <option value="1">Trimester 1</option>
                                        <option value="2">Trimester 2</option>
                                        <option value="3">Trimester 3</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Title</label>
                                <input name="title" required class="w-full p-2 border rounded-lg" placeholder="e.g. Best fruits for pregnancy">
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Food Name (optional)</label>
                                <input name="food_name" class="w-full p-2 border rounded-lg" placeholder="e.g. Avocado">
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Content Type</label>
                                <select name="content_type" class="w-full p-2 border rounded-lg">
                                    <option value="text">Text</option>
                                    <option value="video">Video</option>
                                </select>
                                <p class="text-xs text-gray-400 mt-1">If you choose Video, you can upload a video or paste a URL/YouTube link.</p>
                            </div>

                            <div class="grid grid-cols-1 gap-3">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Video Upload (optional)</label>
                                    <input type="file" name="video_file" accept="video/mp4,video/webm,video/quicktime,video/x-m4v"
                                           class="block w-full text-sm text-gray-500 border rounded-lg p-1 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">Video URL / YouTube URL (optional)</label>
                                    <input name="video_url" class="w-full p-2 border rounded-lg" placeholder="https://youtube.com/watch?v=... or direct mp4 link">
                                </div>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Benefits</label>
                                <textarea name="benefits" rows="5" required class="w-full p-2 border rounded-lg" placeholder="Explain benefits..."></textarea>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Caution (optional)</label>
                                <textarea name="caution" rows="3" class="w-full p-2 border rounded-lg" placeholder="Any warnings..."></textarea>
                            </div>

                            <button name="save_food" class="w-full bg-blue-600 text-white py-2.5 rounded-lg font-bold hover:bg-blue-700 transition">
                                Save Food
                            </button>
                        </form>
                    </div>

                    <div class="lg:col-span-2">
                        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="p-4 border-b flex items-center justify-between">
                                <div>
                                    <h3 class="font-bold text-slate-800">Foods List</h3>
                                    <p class="text-xs text-gray-500">Text or video content.</p>
                                </div>
                            </div>

                            <table class="w-full text-left">
                                <thead class="bg-gray-50 border-b">
                                    <tr>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">ID</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Category</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Trimester</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Title</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Type</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Video</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y">
                                    <?php $res = $conn->query("SELECT * FROM pregnancy_foods ORDER BY id DESC"); ?>
                                    <?php while($f = $res->fetch_assoc()): ?>
                                        <tr class="hover:bg-gray-50">
                                            <td class="p-4 text-sm text-gray-500">#<?= (int)$f['id'] ?></td>
                                            <td class="p-4 text-sm font-semibold"><?= htmlspecialchars($f['category']) ?></td>
                                            <td class="p-4 text-sm text-gray-600"><?= htmlspecialchars($f['trimester'] ?? '') ?></td>
                                            <td class="p-4 text-sm"><?= htmlspecialchars($f['title'] ?? '') ?></td>
                                            <td class="p-4 text-sm">
                                                <span class="px-2 py-1 rounded text-xs font-bold uppercase <?= ($f['content_type'] === 'video') ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700' ?>">
                                                    <?= htmlspecialchars($f['content_type']) ?>
                                                </span>
                                            </td>
                                            <td class="p-4 text-sm">
                                                <?php if (!empty($f['video_url'])): ?>
                                                    <a href="<?= htmlspecialchars($f['video_url']) ?>" target="_blank" class="text-blue-600 hover:underline">Open</a>
                                                <?php else: ?>
                                                    <span class="text-gray-400">—</span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="p-4 text-sm">
                                                <a href="?page=foods&del_food=<?= (int)$f['id'] ?>" class="text-red-600 hover:underline"
                                                   onclick="return confirm('Delete this food item?');">Delete</a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            <?php else: ?>
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div class="bg-white p-6 rounded-xl shadow-sm border border-gray-200 h-fit">
                        <h3 class="text-lg font-bold mb-4 flex items-center">
                            <i class="fas fa-triangle-exclamation mr-2 text-red-500"></i> Add Food To Avoid
                        </h3>

                        <form method="post" class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                                <select name="category" class="w-full p-2 border rounded-lg">
                                    <option value="pregnant">Pregnant</option>
                                    <option value="breastfeeding">Breastfeeding</option>
                                    <option value="baby">Baby</option>
                                </select>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Food Name</label>
                                <input name="food_name" required class="w-full p-2 border rounded-lg" placeholder="e.g. Unpasteurized milk">
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">Reason</label>
                                <textarea name="reason" rows="6" required class="w-full p-2 border rounded-lg" placeholder="Explain why to avoid..."></textarea>
                            </div>

                            <button name="save_avoid" class="w-full bg-red-600 text-white py-2.5 rounded-lg font-bold hover:bg-red-700 transition">
                                Save Avoid Item
                            </button>
                        </form>
                    </div>

                    <div class="lg:col-span-2">
                        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                            <div class="p-4 border-b">
                                <h3 class="font-bold text-slate-800">Avoid List</h3>
                                <p class="text-xs text-gray-500">Foods that should be avoided.</p>
                            </div>

                            <table class="w-full text-left">
                                <thead class="bg-gray-50 border-b">
                                    <tr>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">ID</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Category</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Food</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Reason</th>
                                        <th class="p-4 text-xs font-bold text-gray-600 uppercase">Action</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y">
                                    <?php $res = $conn->query("SELECT * FROM pregnancy_foods_avoid ORDER BY id DESC"); ?>
                                    <?php while($a = $res->fetch_assoc()): ?>
                                        <tr class="hover:bg-gray-50">
                                            <td class="p-4 text-sm text-gray-500">#<?= (int)$a['id'] ?></td>
                                            <td class="p-4 text-sm font-semibold"><?= htmlspecialchars($a['category']) ?></td>
                                            <td class="p-4 text-sm"><?= htmlspecialchars($a['food_name']) ?></td>
                                            <td class="p-4 text-sm text-gray-600"><?= htmlspecialchars($a['reason']) ?></td>
                                            <td class="p-4 text-sm">
                                                <a href="?page=foods&tab=avoid&del_avoid=<?= (int)$a['id'] ?>" class="text-red-600 hover:underline"
                                                   onclick="return confirm('Delete this avoid item?');">Delete</a>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

        <?php elseif($page === "subs"): ?>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <table class="w-full text-left">
                    <thead class="bg-gray-50 border-b">
                        <tr>
                            <th class="p-4 font-semibold text-gray-600">User ID</th>
                            <th class="p-4 font-semibold text-gray-600">Plan</th>
                            <th class="p-4 font-semibold text-gray-600">End Date</th>
                            <th class="p-4 font-semibold text-gray-600">Status</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php
                        $r = $conn->query("SELECT * FROM subscriptions ORDER BY end_date DESC");
                        while($s = $r->fetch_assoc()):
                            $isExpired = strtotime($s['end_date']) < time();
                        ?>
                        <tr class="hover:bg-gray-50">
                            <td class="p-4 font-mono text-sm">#<?= (int)$s['user_id'] ?></td>
                            <td class="p-4">
                                <span class="px-2 py-1 rounded text-xs font-bold uppercase <?= ($s['plan'] ?? '') === 'monthly' ? 'bg-purple-100 text-purple-700' : 'bg-blue-100 text-blue-700' ?>">
                                    <?= htmlspecialchars($s['plan'] ?? '') ?>
                                </span>
                            </td>
                            <td class="p-4 text-sm text-gray-600"><?= htmlspecialchars(date('M d, Y', strtotime($s['end_date'] ?? 'now'))) ?></td>
                            <td class="p-4">
                                <?php if($isExpired): ?>
                                    <span class="text-red-500 text-xs font-bold italic">Expired</span>
                                <?php else: ?>
                                    <span class="text-green-500 text-xs font-bold flex items-center">
                                        <span class="w-2 h-2 bg-green-500 rounded-full mr-2 animate-pulse"></span> Active
                                    </span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>

        <?php elseif($page === "chat"): ?>
            <?php $selectedUser = isset($_GET['uid']) ? (int)$_GET['uid'] : 0; ?>

            <div class="flex gap-6">
                <div class="w-80 bg-white rounded-xl shadow-sm border overflow-y-auto h-[600px]">
                    <div class="p-4 font-bold border-b">Conversations</div>

                    <?php
                    $users = $conn->query("
                        SELECT user_id, MAX(id) as last_id
                        FROM doctor_messages
                        WHERE doctor_id = 1
                        GROUP BY user_id
                        ORDER BY last_id DESC
                    ");

                    while($u = $users->fetch_assoc()):
                        $uid = (int)$u['user_id'];

                        $last = $conn->query("
                            SELECT message, sender
                            FROM doctor_messages
                            WHERE user_id = $uid AND doctor_id = 1
                            ORDER BY id DESC
                            LIMIT 1
                        ")->fetch_assoc();

                        $isActive = ($selectedUser === $uid);
                        $hasUnreplied = (($last['sender'] ?? '') === 'user');
                    ?>
                    <a href="?page=chat&uid=<?= $uid ?>"
                       class="block px-4 py-3 border-b hover:bg-gray-100 <?= $isActive ? 'bg-blue-50' : '' ?>">
                        <div class="flex justify-between items-center">
                            <div>
                                <div class="font-semibold">User #<?= $uid ?></div>
                                <div class="text-xs text-gray-500 truncate max-w-[200px]">
                                    <?= htmlspecialchars($last['message'] ?? '') ?>
                                </div>
                            </div>
                            <?php if($hasUnreplied): ?>
                                <span class="text-xs bg-red-500 text-white px-2 py-1 rounded-full">NEW</span>
                            <?php endif; ?>
                        </div>
                    </a>
                    <?php endwhile; ?>
                </div>

                <div class="flex-1 bg-white rounded-xl shadow-sm border flex flex-col h-[600px]">
                    <?php if($selectedUser <= 0): ?>
                        <div class="flex-1 flex items-center justify-center text-gray-400">
                            Select a conversation
                        </div>
                    <?php else: ?>
                        <div class="p-4 border-b font-bold">
                            Chat with User #<?= $selectedUser ?>
                        </div>

                        <div id="chatMessages" class="flex-1 p-4 overflow-y-auto space-y-3">
                            <?php
                            $stmt = $conn->prepare("
                                SELECT * FROM doctor_messages
                                WHERE user_id = ? AND doctor_id = 1
                                ORDER BY id ASC
                            ");
                            $stmt->bind_param("i", $selectedUser);
                            $stmt->execute();
                            $msgs = $stmt->get_result();

                            while($m = $msgs->fetch_assoc()):
                                $isDoc = (($m['sender'] ?? '') === "doctor");
                            ?>
                            <div class="flex <?= $isDoc ? 'justify-end' : 'justify-start' ?>">
                                <div class="<?= $isDoc ? 'bg-blue-600 text-white' : 'bg-gray-200 text-gray-900' ?> px-3 py-2 rounded-xl max-w-[70%] text-sm space-y-2">
                                    <?php if(!empty($m['image'])): ?>
                                        <img src="<?= htmlspecialchars($m['image']) ?>" class="max-w-full rounded-lg">
                                    <?php endif; ?>

                                    <?php if(!empty($m['audio'])): ?>
                                        <audio controls class="w-full">
                                            <source src="<?= htmlspecialchars($m['audio']) ?>" type="audio/mpeg">
                                        </audio>
                                    <?php endif; ?>

                                    <?php if(!empty($m['message'])): ?>
                                        <div><?= htmlspecialchars($m['message']) ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endwhile; ?>
                        </div>

                        <form method="post" class="p-4 border-t flex gap-2">
                            <input type="hidden" name="user_id" value="<?= $selectedUser ?>">
                            <input name="reply" placeholder="Type reply..." class="flex-1 p-2 bg-gray-50 rounded-lg border" required>
                            <button name="send_reply" class="bg-blue-600 text-white px-4 py-2 rounded-lg font-bold">
                                Send
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>

        <?php else: ?>
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                <p class="text-gray-500">Page not found.</p>
            </div>
        <?php endif; ?>

    </main>
</div>

</body>
</html>
