<?php
/* ============================================================================
   WBMCZ — Request a website / portal to be added
   A member sends a request asking for another website to be made live inside
   a service category. Admin reviews it in admin/website_requests.php.
   Table: website_requests  (created by sspmigration.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()) { redirect('login.php'); }

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

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

/* Self-healing schema so the page works even before sspmigration.php is run */
function wr_ensure_schema($db) {
    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) {}
}
wr_ensure_schema($db);

$success_msg = $_SESSION['flash_success'] ?? '';
$error_msg   = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_success'], $_SESSION['flash_error']);

$pre_cat = isset($_GET['cat']) ? (int)$_GET['cat'] : 0;
$pre_sub = isset($_GET['sub']) ? (int)$_GET['sub'] : 0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_web_request'])) {
    $name = sanitize($_POST['website_name'] ?? '');
    $url  = sanitize($_POST['website_url'] ?? '');
    $cat  = (int)($_POST['category_id'] ?? 0);
    $sub  = (int)($_POST['sub_category_id'] ?? 0);
    $con  = sanitize($_POST['contact_number'] ?? '');
    $why  = sanitize($_POST['reason'] ?? '');

    $open = $db->select("SELECT COUNT(id) AS c FROM website_requests WHERE user_id = ? AND status = 'Pending'", [$user_id]);
    $open_count = !empty($open[0]['c']) ? (int)$open[0]['c'] : 0;

    if ($name === '') {
        $_SESSION['flash_error'] = 'Please enter the website or portal name.';
    } elseif ($open_count >= 5) {
        $_SESSION['flash_error'] = 'You already have 5 pending requests. Please wait until they are reviewed.';
    } else {
        $db->insert(
            "INSERT INTO website_requests (user_id, category_id, sub_category_id, website_name, website_url, contact_number, reason, status)
             VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending')",
            [$user_id, $cat ?: null, $sub ?: null, $name, $url, $con, $why]
        );
        try {
            $db->insert("INSERT INTO notifications (user_id, title, message, type, is_read) VALUES (?, ?, ?, 'general', 0)",
                [$user_id, 'Website request received', 'We received your request for "' . $name . '". Our team will review it shortly.']);
        } catch (\Throwable $e) {}
        $_SESSION['flash_success'] = 'Your request has been sent. We will notify you once it is reviewed.';
    }
    redirect('website_request.php');
}

$my_requests = $db->select("SELECT wr.*, sc.title AS cat_title FROM website_requests wr
                            LEFT JOIN service_categories sc ON sc.id = wr.category_id
                            WHERE wr.user_id = ? ORDER BY wr.id DESC LIMIT 50", [$user_id]);

$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sub_cats = $db->select("SELECT id, category_id, title FROM agency_sub_categories WHERE status = 1 ORDER BY category_id, id");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : ltrim($company_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>Request a Website - <?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=Poppins:wght@600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family:'Inter',sans-serif; } </style>
</head>
<?php
require_once __DIR__ . '/includes/theme.php';
$__menu = theme_user_menu($sidebar_subcats, $all_categories);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'Request a Website',
    'active' => 'services',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
    'state'  => 'pickedCat: ' . ($pre_cat ?: 0),
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
                <div class="max-w-3xl mx-auto pb-20">

                    <?php if ($success_msg): ?>
                    <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl flex items-center">
                        <i class="fas fa-check-circle text-xl mr-3"></i><span class="font-medium"><?php echo htmlspecialchars($success_msg); ?></span>
                    </div>
                    <?php endif; ?>
                    <?php if ($error_msg): ?>
                    <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl flex items-center">
                        <i class="fas fa-exclamation-circle text-xl mr-3"></i><span class="font-medium"><?php echo htmlspecialchars($error_msg); ?></span>
                    </div>
                    <?php endif; ?>

                    <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden mb-8">
                        <div class="px-6 py-5 border-b border-slate-100 bg-slate-50/60">
                            <h3 class="text-lg font-bold text-slate-800"><i class="fas fa-globe text-indigo-600 mr-2"></i> Request a new website / portal</h3>
                            <p class="text-xs text-slate-500 mt-1">Is a website you use missing from our list? Tell us and we will try to make it live for everyone.</p>
                        </div>

                        <form method="POST" class="p-6 space-y-5">
                            <div>
                                <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Website / Portal name <span class="text-rose-500">*</span></label>
                                <input type="text" name="website_name" required placeholder="e.g. e-District West Bengal"
                                       class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>

                            <div>
                                <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Website URL</label>
                                <input type="url" name="website_url" placeholder="https://..."
                                       class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Category</label>
                                    <select name="category_id" x-model.number="pickedCat" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                        <option value="0">— Select category —</option>
                                        <?php foreach ($all_categories as $c): ?>
                                            <option value="<?php echo (int)$c['id']; ?>" <?php echo $pre_cat === (int)$c['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($c['title']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Sub-category</label>
                                    <select name="sub_category_id" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                        <option value="0">— Any —</option>
                                        <?php foreach ($sub_cats as $s): ?>
                                            <option value="<?php echo (int)$s['id']; ?>" data-cat="<?php echo (int)$s['category_id']; ?>"
                                                    x-show="pickedCat === 0 || pickedCat === <?php echo (int)$s['category_id']; ?>"
                                                    <?php echo $pre_sub === (int)$s['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($s['title']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Your contact number</label>
                                <input type="tel" name="contact_number" value="<?php echo htmlspecialchars($user['mobile'] ?? ''); ?>"
                                       class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>

                            <div>
                                <label class="block text-xs font-bold uppercase tracking-wide text-slate-600 mb-1.5">Why do you need it?</label>
                                <textarea name="reason" rows="4" placeholder="Tell us what work you do on this website and how often you need it..."
                                          class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:bg-white focus:outline-none focus:ring-2 focus:ring-indigo-500"></textarea>
                            </div>

                            <button type="submit" name="submit_web_request"
                                    class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-8 py-3.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold shadow-md transition-colors">
                                <i class="fas fa-paper-plane"></i> Send Request
                            </button>
                        </form>
                    </div>

                    <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
                        <div class="px-6 py-4 border-b border-slate-100 bg-slate-50/60 flex items-center justify-between">
                            <h3 class="font-bold text-slate-800">My Requests</h3>
                            <span class="text-xs font-bold text-slate-500"><?php echo count($my_requests); ?></span>
                        </div>
                        <div class="divide-y divide-slate-100">
                            <?php if (empty($my_requests)): ?>
                                <p class="p-10 text-center text-slate-500 text-sm"><i class="fas fa-inbox text-3xl mb-3 text-slate-300 block"></i>You have not requested any website yet.</p>
                            <?php else: foreach ($my_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="px-6 py-4 flex flex-wrap items-start justify-between gap-3">
                                    <div class="min-w-0">
                                        <p class="font-bold text-slate-800"><?php echo htmlspecialchars($r['website_name']); ?></p>
                                        <p class="text-xs text-slate-500 mt-0.5">
                                            <?php echo $r['cat_title'] ? htmlspecialchars($r['cat_title']) . ' · ' : ''; ?>
                                            <?php echo date('d M Y', strtotime($r['created_at'])); ?>
                                        </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; ?>
                                        <?php if (!empty($r['admin_remark'])): ?>
                                            <p class="text-xs text-slate-600 mt-1.5 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2"><b>Admin:</b> <?php echo htmlspecialchars($r['admin_remark']); ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <span class="px-3 py-1 rounded-full text-[11px] font-bold <?php echo $sc; ?> whitespace-nowrap"><?php echo htmlspecialchars($r['status']); ?></span>
                                </div>
                            <?php endforeach; endif; ?>
                        </div>
                    </div>

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