<?php
require_once dirname(__DIR__) . '/config/config.php';
requireLogin();
requireAdmin();

$pdo = getDBConnection();
$error = $success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create' || $action === 'update') {
        $offerId = intval($_POST['offer_id'] ?? 0);
        $data = [
            trim($_POST['badge'] ?? ''),
            $_POST['badge_color'] ?? '#EF4444',
            trim($_POST['badge2'] ?? ''),
            $_POST['badge2_color'] ?? '#10B981',
            $_POST['card_color'] ?? '#FFFFFF',
            $_POST['button_color'] ?? '#F0F0F0',
            trim($_POST['icon'] ?? ''),
            trim($_POST['title'] ?? ''),
            trim($_POST['subtitle'] ?? ''),
            trim($_POST['description'] ?? ''),
            trim($_POST['price_label'] ?? ''),
            trim($_POST['price_main'] ?? ''),
            trim($_POST['price_old'] ?? ''),
            trim($_POST['button_text'] ?? 'Get offer'),
            trim($_POST['button_link'] ?? ''),
            intval($_POST['sort_order'] ?? 0),
            $_POST['status'] ?? 'active'
        ];
        
        if (empty($data[7])) {
            $error = 'Title is required';
        } else {
            if ($action === 'create') {
                $stmt = $pdo->prepare("INSERT INTO offers (badge, badge_color, badge2, badge2_color, card_color, button_color, icon, title, subtitle, description, price_label, price_main, price_old, button_text, button_link, sort_order, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute($data);
                $success = 'Offer created';
            } else {
                $data[] = $offerId;
                $stmt = $pdo->prepare("UPDATE offers SET badge=?, badge_color=?, badge2=?, badge2_color=?, card_color=?, button_color=?, icon=?, title=?, subtitle=?, description=?, price_label=?, price_main=?, price_old=?, button_text=?, button_link=?, sort_order=?, status=? WHERE id=?");
                $stmt->execute($data);
                $success = 'Offer updated';
            }
        }
    } elseif ($action === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM offers WHERE id = ?");
        $stmt->execute([intval($_POST['offer_id'])]);
        $success = 'Offer deleted';
    }
}

$offers = [];
try {
    $offers = $pdo->query("SELECT * FROM offers ORDER BY sort_order ASC, created_at DESC")->fetchAll();
} catch (Exception $e) {}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offers - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0A1628; color: #fff; min-height: 100vh; display: flex; }
        
        .sidebar { width: 260px; background: #0F2744; height: 100vh; position: fixed; left: 0; top: 0; z-index: 100; transition: transform 0.3s; }
        .sidebar-header { padding: 1.5rem; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #1E3A5F; }
        .sidebar-header i { font-size: 1.5rem; color: #F5A623; }
        .sidebar-header span { font-weight: 700; color: #F5A623; font-size: 1.25rem; }
        .sidebar-nav { padding: 1rem 0; }
        .nav-link { display: flex; align-items: center; gap: 12px; padding: 0.875rem 1.5rem; color: #E5E7EB; text-decoration: none; border-left: 3px solid transparent; }
        .nav-link:hover, .nav-link.active { background: #1E3A5F; color: #F5A623; border-left-color: #F5A623; }
        .nav-link i { width: 20px; text-align: center; }
        .nav-divider { height: 1px; background: #1E3A5F; margin: 0.75rem 1.5rem; }
        
        .main { flex: 1; margin-left: 260px; }
        .header { background: #0F2744; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 50; }
        .header-toggle { background: none; border: none; color: #fff; font-size: 1.25rem; cursor: pointer; display: none; }
        
        .content { padding: 1.5rem; }
        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem; }
        .page-title { font-size: 1.5rem; }
        .page-title i { color: #F5A623; }
        
        .btn { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.5rem; border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 600; cursor: pointer; text-decoration: none; white-space: nowrap; }
        .btn-gold { background: #F5A623; color: #0A1628; }
        .btn-navy { background: #1E3A5F; color: #fff; }
        .btn-danger { background: #EF4444; color: #fff; }
        .btn-green { background: #10B981; color: #fff; }
        .btn-sm { padding: 0.5rem 0.85rem; font-size: 0.8rem; }
        
        .alert { padding: 1rem; border-radius: 8px; margin-bottom: 1rem; }
        .alert-success { background: rgba(16,185,129,0.2); border: 1px solid #10B981; color: #10B981; }
        .alert-danger { background: rgba(239,68,68,0.2); border: 1px solid #EF4444; color: #EF4444; }

        /* Offers Table */
        .offers-table { background: #0F2744; border-radius: 12px; overflow: hidden; }
        .offers-table-header {
            display: grid;
            grid-template-columns: 56px 1fr 150px 130px 110px 200px;
            padding: 0.75rem 1.25rem;
            background: #0A1628;
            border-bottom: 1px solid #1E3A5F;
            font-size: 0.78rem;
            color: #F5A623;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .offer-row {
            display: grid;
            grid-template-columns: 56px 1fr 150px 130px 110px 200px;
            padding: 1rem 1.25rem;
            border-bottom: 1px solid #1E3A5F;
            align-items: center;
            gap: 0.5rem;
        }
        .offer-row:last-child { border-bottom: none; }
        .offer-row:hover { background: rgba(255,255,255,0.02); }

        .offer-row-icon {
            width: 42px;
            height: 42px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.15rem;
            flex-shrink: 0;
            border: 1px solid rgba(255,255,255,0.1);
        }
        .offer-row-title { font-weight: 600; font-size: 0.95rem; margin-bottom: 0.2rem; color: #fff; }
        .offer-row-subtitle { font-size: 0.8rem; color: #9CA3AF; }
        .offer-row-badges { display: flex; gap: 0.35rem; flex-wrap: wrap; align-items: center; }
        .offer-row-badge { padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.72rem; font-weight: 700; color: #fff; }
        .offer-row-price { font-weight: 700; color: #F5A623; font-size: 0.95rem; }

        .status-badge { display: inline-block; padding: 0.25rem 0.6rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; }
        .status-active { background: rgba(16,185,129,0.2); color: #10B981; }
        .status-inactive { background: rgba(239,68,68,0.2); color: #EF4444; }

        .offer-row-actions { display: flex; gap: 0.4rem; align-items: center; flex-wrap: nowrap; }
        .offer-row-actions form { margin: 0; }

        /* Preview Modal */
        .preview-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.85); display: none; align-items: center; justify-content: center; z-index: 3000; padding: 1rem; overflow-y: auto; }
        .preview-overlay.active { display: flex; }
        .preview-shell { background: #0A1628; border-radius: 16px; width: 100%; max-width: 420px; overflow: hidden; }
        .preview-shell-header { background: #0F2744; padding: 0.75rem 1rem; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #1E3A5F; }
        .preview-shell-title { font-size: 0.85rem; color: #9CA3AF; }
        .preview-shell-close { background: none; border: none; color: #9CA3AF; font-size: 1.4rem; cursor: pointer; line-height: 1; }
        .preview-body { padding: 1rem; }

        /* Offer card styles (user-side look) */
        .offer-card { background: #fff; border-radius: 16px; padding: 1.5rem; position: relative; display: flex; flex-direction: column; box-shadow: 0 4px 20px rgba(0,0,0,0.15); }
        .offer-badges { position: absolute; top: 16px; left: 16px; display: flex; gap: 0.5rem; flex-wrap: wrap; }
        .offer-badge { padding: 0.4rem 0.75rem; border-radius: 6px; font-size: 0.85rem; font-weight: 700; color: #fff; }
        .offer-icon { font-size: 2.5rem; margin-bottom: 1rem; }
        .offer-title { font-size: 1.5rem; font-weight: 700; margin-bottom: 0.25rem; }
        .offer-subtitle { font-size: 1rem; margin-bottom: 1rem; }
        .offer-desc { font-size: 0.95rem; line-height: 1.6; margin-bottom: 1.5rem; }
        .offer-price-box { border-radius: 16px; padding: 1.25rem 1.5rem; margin-bottom: 1rem; }
        .offer-price-label { font-size: 0.9rem; margin-bottom: 0.25rem; }
        .offer-price-main { font-size: 2rem; font-weight: 700; margin-bottom: 0.25rem; }
        .offer-price-old { font-size: 0.9rem; }
        .offer-btn-preview { display: block; padding: 1rem; border-radius: 12px; text-align: center; font-weight: 600; font-size: 1rem; }

        /* Edit/Create Modal */
        .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: none; align-items: center; justify-content: center; z-index: 2000; padding: 1rem; }
        .modal-overlay.active { display: flex; }
        .modal-content { background: #0F2744; border-radius: 12px; width: 100%; max-width: 600px; max-height: 90vh; overflow-y: auto; }
        .modal-header { padding: 1rem 1.5rem; border-bottom: 1px solid #1E3A5F; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: #0F2744; z-index: 10; }
        .modal-header h3 { margin: 0; color: #F5A623; }
        .modal-close { background: none; border: none; color: #9CA3AF; font-size: 1.5rem; cursor: pointer; line-height: 1; }
        .modal-body { padding: 1.5rem; }
        .modal-footer { padding: 1rem 1.5rem; border-top: 1px solid #1E3A5F; display: flex; gap: 1rem; justify-content: flex-end; position: sticky; bottom: 0; background: #0F2744; }
        
        .form-section { margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid #1E3A5F; }
        .form-section:last-child { border-bottom: none; margin-bottom: 0; padding-bottom: 0; }
        .form-section-title { color: #F5A623; font-size: 0.85rem; font-weight: 600; margin-bottom: 1rem; text-transform: uppercase; letter-spacing: 0.5px; }
        .form-group { margin-bottom: 1rem; }
        .form-label { display: block; margin-bottom: 0.5rem; color: #E5E7EB; font-size: 0.85rem; }
        .form-control { width: 100%; padding: 0.75rem 1rem; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 8px; color: #fff; font-size: 0.9rem; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
        .form-hint { font-size: 0.75rem; color: #9CA3AF; margin-top: 0.25rem; }
        
        .empty { text-align: center; padding: 3rem; color: #9CA3AF; }
        .empty i { font-size: 3rem; color: #1E3A5F; margin-bottom: 1rem; display: block; }
        
        .menu-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 99; display: none; }
        .menu-overlay.active { display: block; }
        
        @media (max-width: 900px) {
            .offers-table-header { display: none; }
            .offer-row { grid-template-columns: 42px 1fr; grid-template-rows: auto auto auto; }
            .offer-row > *:nth-child(3),
            .offer-row > *:nth-child(4),
            .offer-row > *:nth-child(5) { grid-column: 2; }
            .offer-row-actions { grid-column: 1 / -1; }
        }
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-260px); }
            .sidebar.active { transform: translateX(0); }
            .main { margin-left: 0; }
            .header-toggle { display: block; }
            .form-row { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="menu-overlay" id="menuOverlay" onclick="toggleSidebar()"></div>
    
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header"><i class="fas fa-feather-alt"></i><span><?php echo SITE_NAME; ?></span></div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-link"><i class="fas fa-home"></i> Dashboard</a>
            <a href="users.php" class="nav-link"><i class="fas fa-users"></i> Users</a>
            <a href="orders.php" class="nav-link"><i class="fas fa-shopping-cart"></i> Orders</a>
            <a href="fund-requests.php" class="nav-link"><i class="fas fa-money-bill"></i> Fund Requests</a>
            <div class="nav-divider"></div>
            <a href="offers.php" class="nav-link active"><i class="fas fa-tags"></i> Offers</a>
            <a href="banners.php" class="nav-link"><i class="fas fa-ad"></i> Banners</a>
            <a href="support.php" class="nav-link"><i class="fas fa-headset"></i> Support</a>
            <div class="nav-divider"></div>
            <a href="<?php echo SITE_URL; ?>/logout.php" class="nav-link"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    
    <main class="main">
        <header class="header">
            <button class="header-toggle" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
            <span><?php echo htmlspecialchars($_SESSION['name']); ?></span>
        </header>
        
        <div class="content">
            <div class="page-header">
                <h1 class="page-title"><i class="fas fa-tags"></i> Promotional Offers</h1>
                <button class="btn btn-gold" onclick="openCreate()"><i class="fas fa-plus"></i> Add Offer</button>
            </div>
            
            <?php if ($error): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
            <?php if ($success): ?><div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div><?php endif; ?>
            
            <?php if (empty($offers)): ?>
                <div class="empty"><i class="fas fa-tags"></i><h4>No Offers Yet</h4><p>Create your first promotional offer!</p></div>
            <?php else: ?>
                <div class="offers-table">
                    <div class="offers-table-header">
                        <div>Icon</div>
                        <div>Offer</div>
                        <div>Badges</div>
                        <div>Price</div>
                        <div>Status</div>
                        <div>Actions</div>
                    </div>
                    <?php foreach ($offers as $index => $offer):
                        $cardColor = $offer['card_color'] ?? '#FFFFFF';
                        $r = hexdec(substr($cardColor,1,2));
                        $g = hexdec(substr($cardColor,3,2));
                        $b = hexdec(substr($cardColor,5,2));
                        $isLight = ($r * 0.299 + $g * 0.587 + $b * 0.114) > 186;
                        $iconColor = $isLight ? '#333333' : '#ffffff';
                        $priceMain = $offer['price_main'] ?? $offer['price'] ?? '';
                        $hasBadge1 = !empty($offer['badge']);
                        $hasBadge2 = !empty($offer['badge2']);
                        // Use a data attribute approach instead of inline onclick with json
                        $jsonId = 'offerData_' . $index;
                    ?>
                    <div class="offer-row">
                        <!-- Icon -->
                        <div>
                            <div class="offer-row-icon" style="background:<?php echo htmlspecialchars($cardColor); ?>;">
                                <?php if (!empty($offer['icon'])): ?>
                                    <i class="<?php echo htmlspecialchars($offer['icon']); ?>" style="color:<?php echo $iconColor; ?>;"></i>
                                <?php else: ?>
                                    <i class="fas fa-tag" style="color:#9CA3AF;"></i>
                                <?php endif; ?>
                            </div>
                        </div>
                        <!-- Info -->
                        <div>
                            <div class="offer-row-title"><?php echo htmlspecialchars($offer['title']); ?></div>
                            <?php if (!empty($offer['subtitle'])): ?>
                            <div class="offer-row-subtitle"><?php echo htmlspecialchars($offer['subtitle']); ?></div>
                            <?php endif; ?>
                        </div>
                        <!-- Badges -->
                        <div class="offer-row-badges">
                            <?php if ($hasBadge1): ?>
                                <span class="offer-row-badge" style="background:<?php echo htmlspecialchars($offer['badge_color'] ?? '#EF4444'); ?>;"><?php echo htmlspecialchars($offer['badge']); ?></span>
                            <?php endif; ?>
                            <?php if ($hasBadge2): ?>
                                <span class="offer-row-badge" style="background:<?php echo htmlspecialchars($offer['badge2_color'] ?? '#10B981'); ?>;"><?php echo htmlspecialchars($offer['badge2']); ?></span>
                            <?php endif; ?>
                            <?php if (!$hasBadge1 && !$hasBadge2): ?>
                                <span style="color:#6B7280;font-size:0.8rem;">—</span>
                            <?php endif; ?>
                        </div>
                        <!-- Price -->
                        <div class="offer-row-price">
                            <?php if (!empty($priceMain)): ?>
                                <?php echo htmlspecialchars($priceMain); ?>
                            <?php else: ?>
                                <span style="color:#6B7280;font-size:0.8rem;">—</span>
                            <?php endif; ?>
                        </div>
                        <!-- Status -->
                        <div>
                            <span class="status-badge <?php echo $offer['status'] === 'active' ? 'status-active' : 'status-inactive'; ?>"><?php echo ucfirst($offer['status']); ?></span>
                            <div style="font-size:0.7rem;color:#6B7280;margin-top:0.3rem;">Sort: <?php echo $offer['sort_order']; ?></div>
                        </div>
                        <!-- Actions - using data-index to avoid inline JSON breaking onclick -->
                        <div class="offer-row-actions">
                            <button class="btn btn-green btn-sm" data-index="<?php echo $index; ?>" onclick="previewOffer(this.dataset.index)"><i class="fas fa-eye"></i> View</button>
                            <button class="btn btn-navy btn-sm" data-index="<?php echo $index; ?>" onclick="editOffer(this.dataset.index)"><i class="fas fa-edit"></i> Edit</button>
                            <form method="POST" onsubmit="return confirm('Delete this offer?')">
                                <?php echo csrfTokenField(); ?>
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="offer_id" value="<?php echo $offer['id']; ?>">
                                <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Offer data stored safely in a JS array -->
                <script>
                var offersData = <?php echo json_encode(array_values($offers), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP); ?>;
                </script>
            <?php endif; ?>
        </div>
    </main>

    <!-- Preview Modal -->
    <div class="preview-overlay" id="previewModal">
        <div class="preview-shell">
            <div class="preview-shell-header">
                <span class="preview-shell-title"><i class="fas fa-mobile-alt"></i> User Preview</span>
                <button class="preview-shell-close" onclick="closePreview()">&times;</button>
            </div>
            <div class="preview-body" id="previewBody"></div>
        </div>
    </div>
    
    <!-- Edit/Create Modal -->
    <div class="modal-overlay" id="offerModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3 id="modalTitle">Create Offer</h3>
                <button class="modal-close" onclick="closeModal()">&times;</button>
            </div>
            <form method="POST" id="offerForm">
                <?php echo csrfTokenField(); ?>
                <input type="hidden" name="action" id="formAction" value="create">
                <input type="hidden" name="offer_id" id="offerId">
                <div class="modal-body">
                    
                    <div class="form-section">
                        <div class="form-section-title">Badges & Card</div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">Badge 1 Text</label>
                                <input type="text" name="badge" id="offerBadge" class="form-control" placeholder="87% off">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Badge 1 Color</label>
                                <input type="color" name="badge_color" id="offerBadgeColor" class="form-control" value="#EF4444" style="height:42px;">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">Badge 2 Text <small style="color:#9CA3AF;">(optional)</small></label>
                                <input type="text" name="badge2" id="offerBadge2" class="form-control" placeholder="Limited Time">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Badge 2 Color</label>
                                <input type="color" name="badge2_color" id="offerBadge2Color" class="form-control" value="#10B981" style="height:42px;">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Card Background Color</label>
                            <input type="color" name="card_color" id="offerCardColor" class="form-control" value="#FFFFFF" style="height:42px;">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Button Color</label>
                            <input type="color" name="button_color" id="offerButtonColor" class="form-control" value="#F0F0F0" style="height:42px;">
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <div class="form-section-title">Basic Info</div>
                        <div class="form-group">
                            <label class="form-label">Icon (FontAwesome)</label>
                            <input type="text" name="icon" id="offerIcon" class="form-control" placeholder="fas fa-shield-alt">
                            <div class="form-hint">e.g. fas fa-rocket, fas fa-bolt, fab fa-instagram</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Title *</label>
                            <input type="text" name="title" id="offerTitle" class="form-control" required placeholder="FastVPN">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Subtitle / Category</label>
                            <input type="text" name="subtitle" id="offerSubtitle" class="form-control" placeholder="Security">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Description</label>
                            <textarea name="description" id="offerDescription" class="form-control" rows="2" placeholder="Save 87% on FastVPN. Your first month is just $0.99."></textarea>
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <div class="form-section-title">Price Box</div>
                        <div class="form-group">
                            <label class="form-label">Price Label (small text above)</label>
                            <input type="text" name="price_label" id="offerPriceLabel" class="form-control" placeholder="From">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Main Price (big text)</label>
                            <input type="text" name="price_main" id="offerPriceMain" class="form-control" placeholder="$0.99/mo">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Old Price Text (small text below)</label>
                            <input type="text" name="price_old" id="offerPriceOld" class="form-control" placeholder="Instead of $7.88/mo">
                        </div>
                    </div>
                    
                    <div class="form-section">
                        <div class="form-section-title">Button & Settings</div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">Button Text</label>
                                <input type="text" name="button_text" id="offerButtonText" class="form-control" value="Get offer">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Button Link</label>
                                <input type="text" name="button_link" id="offerButtonLink" class="form-control" placeholder="/user/smm.php">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label">Sort Order</label>
                                <input type="number" name="sort_order" id="offerSortOrder" class="form-control" value="0">
                            </div>
                            <div class="form-group">
                                <label class="form-label">Status</label>
                                <select name="status" id="offerStatus" class="form-control">
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-navy" onclick="closeModal()">Cancel</button>
                    <button type="submit" class="btn btn-gold">Save Offer</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        function toggleSidebar() { 
            document.getElementById('sidebar').classList.toggle('active'); 
            document.getElementById('menuOverlay').classList.toggle('active'); 
        }

        function closeModal() { document.getElementById('offerModal').classList.remove('active'); }
        function closePreview() { document.getElementById('previewModal').classList.remove('active'); }
        
        function openCreate() {
            document.getElementById('modalTitle').textContent = 'Create Offer';
            document.getElementById('formAction').value = 'create';
            document.getElementById('offerForm').reset();
            document.getElementById('offerBadgeColor').value = '#EF4444';
            document.getElementById('offerBadge2Color').value = '#10B981';
            document.getElementById('offerCardColor').value = '#FFFFFF';
            document.getElementById('offerButtonColor').value = '#F0F0F0';
            document.getElementById('offerButtonText').value = 'Get offer';
            document.getElementById('offerModal').classList.add('active');
        }

        // Uses offersData array instead of inline JSON to avoid any quote/encoding issues
        function editOffer(index) {
            var o = offersData[index];
            document.getElementById('modalTitle').textContent = 'Edit Offer';
            document.getElementById('formAction').value = 'update';
            document.getElementById('offerId').value = o.id;
            document.getElementById('offerBadge').value = o.badge || '';
            document.getElementById('offerBadgeColor').value = o.badge_color || '#EF4444';
            document.getElementById('offerBadge2').value = o.badge2 || '';
            document.getElementById('offerBadge2Color').value = o.badge2_color || '#10B981';
            document.getElementById('offerCardColor').value = o.card_color || '#FFFFFF';
            document.getElementById('offerButtonColor').value = o.button_color || '#F0F0F0';
            document.getElementById('offerIcon').value = o.icon || '';
            document.getElementById('offerTitle').value = o.title || '';
            document.getElementById('offerSubtitle').value = o.subtitle || '';
            document.getElementById('offerDescription').value = o.description || '';
            document.getElementById('offerPriceLabel').value = o.price_label || '';
            document.getElementById('offerPriceMain').value = o.price_main || o.price || '';
            document.getElementById('offerPriceOld').value = o.price_old || o.price_subtext || '';
            document.getElementById('offerButtonText').value = o.button_text || 'Get offer';
            document.getElementById('offerButtonLink').value = o.button_link || '';
            document.getElementById('offerSortOrder').value = o.sort_order || 0;
            document.getElementById('offerStatus').value = o.status || 'active';
            document.getElementById('offerModal').classList.add('active');
        }

        function previewOffer(index) {
            var o = offersData[index];
            var cardColor = o.card_color || '#FFFFFF';
            var r = parseInt(cardColor.substr(1,2),16);
            var g = parseInt(cardColor.substr(3,2),16);
            var b = parseInt(cardColor.substr(5,2),16);
            var isLight = (r * 0.299 + g * 0.587 + b * 0.114) > 186;
            var textColor     = isLight ? '#1a1a1a' : '#ffffff';
            var subtitleColor = isLight ? '#666666' : '#cccccc';
            var descColor     = isLight ? '#444444' : '#bbbbbb';
            var priceBoxBg    = isLight ? '#f8f8f8' : 'rgba(255,255,255,0.1)';
            var priceLabelClr = isLight ? '#888888' : '#aaaaaa';
            var btnBorder     = isLight ? '#e0e0e0' : 'rgba(255,255,255,0.2)';
            var hasBadge1 = o.badge && o.badge.trim() !== '';
            var hasBadge2 = o.badge2 && o.badge2.trim() !== '';
            var priceMain = o.price_main || o.price || '';

            var html = '<div class="offer-card" style="background:' + cardColor + ';color:' + textColor + ';">';

            // Badges
            if (hasBadge1 || hasBadge2) {
                html += '<div class="offer-badges">';
                if (hasBadge1) html += '<span class="offer-badge" style="background:' + esc(o.badge_color||'#EF4444') + ';">' + esc(o.badge) + '</span>';
                if (hasBadge2) html += '<span class="offer-badge" style="background:' + esc(o.badge2_color||'#10B981') + ';">' + esc(o.badge2) + '</span>';
                html += '</div>';
            }

            // Icon
            if (o.icon) {
                var mt = (hasBadge1 || hasBadge2) ? '2.5rem' : '0.5rem';
                html += '<div class="offer-icon" style="color:' + textColor + ';margin-top:' + mt + ';"><i class="' + esc(o.icon) + '"></i></div>';
            } else if (hasBadge1 || hasBadge2) {
                html += '<div style="margin-top:2.5rem;"></div>';
            }

            html += '<h4 class="offer-title" style="color:' + textColor + ';">' + esc(o.title) + '</h4>';
            if (o.subtitle) html += '<p class="offer-subtitle" style="color:' + subtitleColor + ';">' + esc(o.subtitle) + '</p>';
            if (o.description) html += '<p class="offer-desc" style="color:' + descColor + ';">' + esc(o.description) + '</p>';

            // Price box
            if (priceMain) {
                html += '<div class="offer-price-box" style="background:' + priceBoxBg + ';">';
                if (o.price_label) html += '<div class="offer-price-label" style="color:' + priceLabelClr + ';">' + esc(o.price_label) + '</div>';
                html += '<div class="offer-price-main" style="color:' + textColor + ';">' + esc(priceMain) + '</div>';
                if (o.price_old || o.price_subtext) html += '<div class="offer-price-old" style="color:#999;">' + esc(o.price_old || o.price_subtext) + '</div>';
                html += '</div>';
            }

            html += '<div class="offer-btn-preview" style="background:' + esc(o.button_color||'#F0F0F0') + ';color:' + textColor + ';border:1px solid ' + btnBorder + ';">' + esc(o.button_text || 'Get offer') + '</div>';
            html += '</div>';

            document.getElementById('previewBody').innerHTML = html;
            document.getElementById('previewModal').classList.add('active');
        }

        function esc(str) {
            if (!str) return '';
            var d = document.createElement('div');
            d.appendChild(document.createTextNode(String(str)));
            return d.innerHTML;
        }

        document.getElementById('previewModal').addEventListener('click', function(e) { if (e.target === this) closePreview(); });
        document.getElementById('offerModal').addEventListener('click', function(e) { if (e.target === this) closeModal(); });
    </script>
</body>
</html>