<?php
/* ============================================================================
   ADMIN — Website / portal requests sent by members (website_request.php)
   ============================================================================ */
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_services');

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$me_id = $_SESSION['user_id'];

try {
    $db->getConnection()->query("CREATE TABLE IF NOT EXISTS website_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL, category_id INT NULL, sub_category_id INT NULL,
        website_name VARCHAR(200) NOT NULL, website_url VARCHAR(255) NULL,
        contact_number VARCHAR(30) NULL, reason TEXT NULL,
        status VARCHAR(20) NOT NULL DEFAULT 'Pending', admin_remark TEXT NULL,
        created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP NULL DEFAULT NULL,
        KEY idx_wr_user (user_id), KEY idx_wr_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
} catch (\Throwable $e) {}

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

if (isset($_POST['set_status'])) {
    $rid    = (int)$_POST['request_id'];
    $status = in_array($_POST['set_status'], ['Approved', 'Rejected', 'Pending'], true) ? $_POST['set_status'] : 'Pending';
    $remark = sanitize($_POST['admin_remark'] ?? '');

    $db->insert("UPDATE website_requests SET status = ?, admin_remark = ?, updated_at = NOW() WHERE id = ?", [$status, $remark, $rid]);

    $r = $db->select("SELECT user_id, website_name FROM website_requests WHERE id = ?", [$rid]);
    if (!empty($r)) {
        try {
            $db->insert("INSERT INTO notifications (user_id, title, message, type, is_read) VALUES (?, ?, ?, 'general', 0)", [
                (int)$r[0]['user_id'],
                'Website request ' . strtolower($status),
                'Your request for "' . $r[0]['website_name'] . '" was ' . strtolower($status) . '.' . ($remark ? ' Note: ' . $remark : '')
            ]);
        } catch (\Throwable $e) {}
    }
    $_SESSION['flash_success'] = "Request marked as $status.";
    redirect('website_requests.php');
}

$f = isset($_GET['status']) ? $_GET['status'] : 'Pending';
$where = ''; $params = [];
if (in_array($f, ['Pending', 'Approved', 'Rejected'], true)) { $where = "WHERE wr.status = ?"; $params[] = $f; }

$requests = $db->select("SELECT wr.*, u.name AS user_name, u.mobile, u.email, sc.title AS cat_title
                         FROM website_requests wr
                         JOIN users u ON u.id = wr.user_id
                         LEFT JOIN service_categories sc ON sc.id = wr.category_id
                         $where ORDER BY wr.id DESC LIMIT 300", $params);

$counts = ['Pending' => 0, 'Approved' => 0, 'Rejected' => 0];
foreach ($db->select("SELECT status, COUNT(id) AS c FROM website_requests GROUP BY status") as $r) {
    $counts[$r['status']] = (int)$r['c'];
}

$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');
?>
<!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>Website Requests - <?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">Website Requests</p>
                    <p class="text-[11px] text-slate-400">Members asking for a new portal to be made live</p>
                </div>
            </div>
        </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; ?>

        <div class="flex flex-wrap gap-2 mb-5">
            <?php foreach (['Pending', 'Approved', 'Rejected', 'all'] as $s):
                $on = ($f === $s);
                $lbl = $s === 'all' ? 'All' : $s . ' (' . $counts[$s] . ')';
            ?>
                <a href="?status=<?php echo $s; ?>" 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; ?></a>
            <?php endforeach; ?>
        </div>

        <div class="bg-white rounded-2xl border border-slate-200 overflow-hidden">
            <?php if (empty($requests)): ?>
                <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 requests in this list.</p>
            <?php else: ?>
            <div class="divide-y divide-slate-100">
                <?php foreach ($requests as $r):
                    $sc = ['Pending' => 'bg-amber-50 text-amber-700', 'Approved' => 'bg-emerald-50 text-emerald-700', 'Rejected' => 'bg-rose-50 text-rose-700'][$r['status']] ?? 'bg-slate-100 text-slate-600';
                ?>
                <div class="p-5">
                    <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($r['website_name']); ?></p>
                            <?php if (!empty($r['website_url'])): ?>
                                <a href="<?php echo htmlspecialchars($r['website_url']); ?>" target="_blank" rel="noopener" class="text-xs text-indigo-600 font-semibold break-all"><?php echo htmlspecialchars($r['website_url']); ?></a>
                            <?php endif; ?>
                            <p class="text-xs text-slate-500 mt-1.5">
                                <i class="fas fa-user text-slate-400 mr-1"></i><?php echo htmlspecialchars($r['user_name']); ?> (#<?php echo (int)$r['user_id']; ?>)
                                · <?php echo htmlspecialchars($r['contact_number'] ?: $r['mobile']); ?>
                                <?php if ($r['cat_title']): ?> · <?php echo htmlspecialchars($r['cat_title']); ?><?php endif; ?>
                                · <?php echo date('d M Y, h:i A', strtotime($r['created_at'])); ?>
                            </p>
                            <?php if (!empty($r['reason'])): ?>
                                <p class="text-xs text-slate-600 mt-2 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2"><?php echo nl2br(htmlspecialchars($r['reason'])); ?></p>
                            <?php endif; ?>
                            <?php if (!empty($r['admin_remark'])): ?>
                                <p class="text-xs text-slate-600 mt-2"><b>Remark:</b> <?php echo htmlspecialchars($r['admin_remark']); ?></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 <?php echo $sc; ?>"><?php echo htmlspecialchars($r['status']); ?></span>
                            <button type="button" @click="open = (open === <?php echo (int)$r['id']; ?> ? null : <?php echo (int)$r['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>

                    <form method="POST" x-show="open === <?php echo (int)$r['id']; ?>" x-cloak class="mt-4 grid grid-cols-1 sm:grid-cols-[1fr,auto,auto] gap-2 items-center">
                        <input type="hidden" name="request_id" value="<?php echo (int)$r['id']; ?>">
                        <input type="text" name="admin_remark" value="<?php echo htmlspecialchars($r['admin_remark'] ?? '', ENT_QUOTES); ?>" placeholder="Remark for the member (optional)"
                               class="w-full px-4 py-2.5 bg-slate-50 border border-slate-200 rounded-lg text-sm">
                        <button type="submit" name="set_status" value="Approved" class="px-5 py-2.5 rounded-lg bg-emerald-600 hover:bg-emerald-700 text-white font-bold text-sm whitespace-nowrap"><i class="fas fa-check mr-1"></i> Approve</button>
                        <button type="submit" name="set_status" value="Rejected" class="px-5 py-2.5 rounded-lg bg-rose-600 hover:bg-rose-700 text-white font-bold text-sm whitespace-nowrap"><i class="fas fa-xmark mr-1"></i> Reject</button>
                    </form>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>
    </div>
</div>
</body>
</html>
