<?php
/**
 * Admin — Quote / Contact Inquiries
 * Path: admin/inquiries.php
 */
require_once 'layout-header.php';

$msg_success = '';
$search      = trim($_GET['search'] ?? '');
$page        = max(1, intval($_GET['page'] ?? 1));
$per_page    = 20;
$offset      = ($page - 1) * $per_page;
$view_id     = isset($_GET['view']) ? intval($_GET['view']) : 0;

if (!$conn) {
    echo "<main class='flex-1 p-6'><div class='p-4 bg-red-950/40 border border-red-800 text-red-200 text-sm rounded-xl'>ডাটাবেজ কানেক্টেড নেই! প্রথমে <strong>install-four.php</strong> রান করুন।</div></main>";
    require_once 'layout-footer.php';
    exit;
}

$prefix = DB_PREFIX;

if (isset($_GET['delete']) && intval($_GET['delete']) > 0) {
    delete_contact_inquiry(intval($_GET['delete']));
    $msg_success = 'ইনকোয়ারি মুছে ফেলা হয়েছে।';
}

if (isset($_GET['mark_read']) && intval($_GET['mark_read']) > 0) {
    mark_inquiry_read(intval($_GET['mark_read']));
    $msg_success = 'পঠিত হিসেবে চিহ্নিত করা হয়েছে।';
}

if (isset($_GET['mark_all_read'])) {
    $conn->query("UPDATE `{$prefix}contact_inquiries` SET is_read = 1 WHERE is_read = 0");
    $msg_success = 'সব ইনকোয়ারি পঠিত চিহ্নিত করা হয়েছে।';
}

// View single — auto mark read
$viewing = null;
if ($view_id > 0) {
    $viewing = get_contact_inquiry_by_id($view_id);
    if ($viewing && !$viewing['is_read']) mark_inquiry_read($view_id);
}

// Fetch list
$where = '';
$params = [];
$types = '';
if ($search) {
    $where = " WHERE name LIKE ? OR phone LIKE ? OR email LIKE ? OR service LIKE ? OR message LIKE ?";
    $like = '%' . $search . '%';
    $params = array_fill(0, 5, $like);
    $types = 'sssss';
}

$count_sql = "SELECT COUNT(*) as cnt FROM `{$prefix}contact_inquiries`" . $where;
if ($search) {
    $cs = $conn->prepare($count_sql);
    $cs->bind_param($types, ...$params);
    $cs->execute();
    $total = (int)$cs->get_result()->fetch_assoc()['cnt'];
    $cs->close();
} else {
    $total = count_contact_inquiries();
}

$sql = "SELECT * FROM `{$prefix}contact_inquiries`" . $where . " ORDER BY created_at DESC LIMIT {$per_page} OFFSET {$offset}";
if ($search) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}

$inquiries = [];
if ($result) while ($row = $result->fetch_assoc()) $inquiries[] = $row;

$unread_count = count_contact_inquiries(true);
$total_pages = max(1, ceil($total / $per_page));
?>

<main class="flex-1 p-6 md:p-8 space-y-6">

    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 border-b border-slate-800/80 pb-5">
        <div>
            <h1 class="text-2xl font-black text-white uppercase tracking-wider">Quote Requests</h1>
            <p class="text-xs text-slate-400 mt-1">
                Contact ফর্ম থেকে আসা কোটেশন — মোট <?php echo $total; ?>টি
                <?php if ($unread_count > 0): ?>
                <span class="ml-2 bg-rose-500/20 text-rose-400 px-2 py-0.5 rounded-full font-bold"><?php echo $unread_count; ?> নতুন</span>
                <?php endif; ?>
            </p>
        </div>
        <?php if ($unread_count > 0): ?>
        <a href="?mark_all_read=1" class="text-xs font-bold text-sky-400 hover:text-sky-300 uppercase">Mark All Read</a>
        <?php endif; ?>
    </div>

    <?php if ($msg_success): ?>
    <div class="p-4 bg-emerald-950/40 border border-emerald-800 text-emerald-200 text-xs rounded-xl flex items-center">
        <i class="fa-solid fa-circle-check mr-3"></i><?php echo $msg_success; ?>
    </div>
    <?php endif; ?>

    <form method="get" class="flex gap-3">
        <input type="text" name="search" value="<?php echo htmlspecialchars($search); ?>"
            placeholder="নাম, ফোন, ইমেইল, সার্ভিস দিয়ে খুঁজুন..."
            class="flex-1 bg-slate-900 border border-slate-800 rounded-xl px-4 py-3 text-sm text-slate-100">
        <button type="submit" class="bg-sky-500 hover:bg-sky-600 text-slate-950 font-bold px-6 py-3 rounded-xl text-xs uppercase">
            <i class="fa-solid fa-magnifying-glass"></i> Search
        </button>
        <?php if ($search): ?><a href="inquiries.php" class="bg-slate-800 text-slate-400 px-4 py-3 rounded-xl text-xs flex items-center">Clear</a><?php endif; ?>
    </form>

    <?php if ($viewing): ?>
    <!-- Single View -->
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl p-6 space-y-4">
        <div class="flex items-center justify-between border-b border-slate-800 pb-4">
            <h2 class="text-sm font-black uppercase text-sky-400">Inquiry #<?php echo $viewing['id']; ?></h2>
            <a href="inquiries.php" class="text-xs text-slate-400 hover:text-white"><i class="fa-solid fa-arrow-left mr-1"></i> Back</a>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Name</span><p class="text-white font-semibold"><?php echo htmlspecialchars($viewing['name']); ?></p></div>
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Phone</span>
                <a href="tel:<?php echo htmlspecialchars($viewing['phone']); ?>" class="text-sky-400 font-semibold hover:underline"><?php echo htmlspecialchars($viewing['phone']); ?></a></div>
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Email</span>
                <a href="mailto:<?php echo htmlspecialchars($viewing['email']); ?>" class="text-sky-400 font-semibold hover:underline"><?php echo htmlspecialchars($viewing['email']); ?></a></div>
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Service</span><p class="text-white"><?php echo htmlspecialchars($viewing['service'] ?: '—'); ?></p></div>
            <div class="md:col-span-2"><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Message</span>
                <p class="text-slate-300 leading-relaxed bg-slate-950 p-4 rounded-xl border border-slate-800"><?php echo nl2br(htmlspecialchars($viewing['message'] ?: '—')); ?></p></div>
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">Date</span><p class="text-slate-400 text-xs"><?php echo date('d M Y, h:i A', strtotime($viewing['created_at'])); ?></p></div>
            <div><span class="text-[10px] font-bold uppercase text-slate-500 block mb-1">IP</span><p class="text-slate-400 text-xs font-mono"><?php echo htmlspecialchars($viewing['ip_address'] ?? '—'); ?></p></div>
        </div>
        <div class="flex gap-2 pt-2">
            <a href="tel:<?php echo htmlspecialchars($viewing['phone']); ?>" class="bg-emerald-600 hover:bg-emerald-500 text-white px-5 py-2.5 rounded-xl text-xs font-bold"><i class="fa-solid fa-phone mr-1"></i> Call</a>
            <a href="?delete=<?php echo $viewing['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="bg-red-950/50 border border-red-800 text-red-400 px-4 py-2.5 rounded-xl text-xs font-bold"><i class="fa-solid fa-trash"></i></a>
        </div>
    </div>
    <?php endif; ?>

    <!-- List -->
    <?php if (empty($inquiries)): ?>
    <div class="text-center py-16 text-slate-500">
        <i class="fa-solid fa-inbox text-3xl mb-3 block opacity-30"></i>
        <p class="text-sm">কোনো কোটেশন রিকোয়েস্ট নেই।</p>
    </div>
    <?php else: ?>
    <div class="bg-slate-900 border border-slate-800/80 rounded-2xl overflow-hidden">
        <div class="overflow-x-auto">
            <table class="w-full text-left text-sm">
                <thead>
                    <tr class="bg-slate-950 text-slate-400 text-xs font-bold uppercase border-b border-slate-800">
                        <th class="p-4 pl-6">Client</th>
                        <th class="p-4 hidden md:table-cell">Service</th>
                        <th class="p-4 hidden lg:table-cell">Contact</th>
                        <th class="p-4">Date</th>
                        <th class="p-4 text-right pr-6">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-800">
                    <?php foreach ($inquiries as $inq): ?>
                    <tr class="hover:bg-slate-800/30 transition-colors <?php echo !$inq['is_read'] ? 'bg-sky-950/10' : ''; ?>">
                        <td class="p-4 pl-6">
                            <div class="flex items-center gap-2">
                                <?php if (!$inq['is_read']): ?><span class="w-2 h-2 bg-sky-400 rounded-full flex-shrink-0"></span><?php endif; ?>
                                <span class="font-bold text-white text-sm"><?php echo htmlspecialchars($inq['name']); ?></span>
                            </div>
                            <p class="text-[10px] text-slate-500 mt-0.5 line-clamp-1 md:hidden"><?php echo htmlspecialchars($inq['phone']); ?></p>
                        </td>
                        <td class="p-4 hidden md:table-cell">
                            <span class="text-xs text-slate-400"><?php echo htmlspecialchars($inq['service'] ?: '—'); ?></span>
                        </td>
                        <td class="p-4 hidden lg:table-cell">
                            <p class="text-xs text-sky-400"><?php echo htmlspecialchars($inq['phone']); ?></p>
                            <p class="text-[10px] text-slate-500"><?php echo htmlspecialchars($inq['email']); ?></p>
                        </td>
                        <td class="p-4 text-xs text-slate-500 whitespace-nowrap"><?php echo date('d M, h:i A', strtotime($inq['created_at'])); ?></td>
                        <td class="p-4 text-right pr-6">
                            <div class="inline-flex gap-1">
                                <a href="?view=<?php echo $inq['id']; ?>" class="p-2 bg-slate-800 hover:bg-sky-500 text-sky-400 hover:text-slate-950 rounded-lg text-xs" title="View"><i class="fa-solid fa-eye"></i></a>
                                <a href="tel:<?php echo htmlspecialchars($inq['phone']); ?>" class="p-2 bg-slate-800 hover:bg-emerald-500 text-emerald-400 hover:text-white rounded-lg text-xs"><i class="fa-solid fa-phone"></i></a>
                                <a href="?delete=<?php echo $inq['id']; ?>" onclick="return confirm('মুছে ফেলবেন?');" class="p-2 bg-slate-800 hover:bg-red-500 text-red-400 hover:text-white rounded-lg text-xs"><i class="fa-solid fa-trash"></i></a>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if ($total_pages > 1): ?>
    <div class="flex justify-center gap-2">
        <?php for ($p = 1; $p <= $total_pages; $p++): ?>
        <a href="?page=<?php echo $p; ?><?php echo $search ? '&search='.urlencode($search) : ''; ?>"
            class="px-3 py-1.5 rounded-lg text-xs font-bold <?php echo $p === $page ? 'bg-sky-500 text-slate-950' : 'bg-slate-800 text-slate-400'; ?>"><?php echo $p; ?></a>
        <?php endfor; ?>
    </div>
    <?php endif; ?>
    <?php endif; ?>

</main>

<?php require_once 'layout-footer.php'; ?>
