<style>
.form-header-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    color: white;
    padding: 2rem;
    border-radius: 15px;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(114, 165, 101, 0.2);
}

.form-card-modern {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    margin-bottom: 1.5rem;
    border: none;
    overflow: hidden;
}

.form-card-modern .card-header {
    background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
    border-bottom: 2px solid #e2e8f0;
    padding: 1.25rem 1.5rem;
    font-weight: 600;
    color: #2d3748;
}

.form-card-modern .card-body {
    padding: 2rem;
}

.form-label-modern {
    font-weight: 600;
    color: #2d3748;
    margin-bottom: 0.5rem;
    font-size: 0.875rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-control-modern {
    border-radius: 10px;
    border: 2px solid #e2e8f0;
    padding: 0.75rem 1rem;
    transition: all 0.3s ease;
}

.form-control-modern:focus {
    border-color: #72A565;
    box-shadow: 0 0 0 3px rgba(114, 165, 101, 0.1);
    outline: none;
}

.btn-submit-modern {
    background: linear-gradient(135deg, #72A565 0%, #91A134 100%);
    border: none;
    color: white;
    padding: 0.75rem 2rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(114, 165, 101, 0.3);
}

.btn-submit-modern:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 12px rgba(114, 165, 101, 0.4);
    color: white;
}

.info-box {
    background: #f7fafc;
    border-left: 4px solid #72A565;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
}

.info-box i {
    color: #72A565;
    margin-right: 0.5rem;
}

.form-check-input:checked {
    background-color: #72A565;
    border-color: #72A565;
}

.tier-badge {
    display: inline-block;
    padding: 0.5rem 1rem;
    border-radius: 8px;
    font-weight: 600;
    font-size: 0.875rem;
    margin-right: 0.5rem;
}

.tier-badge.bronze { background: linear-gradient(135deg, #cd7f32 0%, #b87333 100%); color: white; }
.tier-badge.silver { background: linear-gradient(135deg, #c0c0c0 0%, #a8a8a8 100%); color: white; }
.tier-badge.gold { background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); color: #333; }
.tier-badge.platinum { background: linear-gradient(135deg, #e5e4e2 0%, #d3d3d3 100%); color: #333; }

.reward-card {
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    padding: 1rem;
    margin-bottom: 1rem;
    transition: all 0.3s ease;
}

.reward-card:hover {
    border-color: #72A565;
    box-shadow: 0 4px 12px rgba(114, 165, 101, 0.15);
}

.reward-card.disabled {
    opacity: 0.6;
    background: #f7fafc;
}
</style>

<!-- Header Section -->
<div class="form-header-modern">
    <div class="d-flex justify-content-between align-items-center">
        <div>
            <h2 class="mb-2">
                <i class="fa-solid fa-star"></i> Loyalty Program Management
            </h2>
            <p class="mb-0 opacity-75">Configure point earning rates, tier thresholds, rewards, and special promotions</p>
        </div>
        <div>
            <a href="<?php echo base_url('loyalty/history'); ?>" class="btn btn-light btn-modern me-2">
                <i class="fa-solid fa-history"></i> View History
            </a>
        </div>
    </div>
</div>

<!-- Point Earning Settings -->
<div class="form-card-modern">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fa-solid fa-coins text-primary"></i> Point Earning Rate
        </h5>
    </div>
    <div class="card-body">
        <form id="settingsForm" method="post" action="<?php echo base_url('loyalty/updateSettings'); ?>">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label-modern">Points Per Dollar Spent <span class="text-danger">*</span></label>
                    <input type="number" step="0.1" min="0" name="pointsPerDollar" 
                        class="form-control form-control-modern" 
                        value="<?php echo isset($settings['pointsPerDollar']) ? $settings['pointsPerDollar'] : '1.0'; ?>" 
                        required>
                    <small class="text-muted">Number of points customers earn per dollar spent on orders</small>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label-modern">Point Earning Rate <span class="text-danger">*</span></label>
                    <input type="number" step="0.1" min="0" name="pointEarningRate" 
                        class="form-control form-control-modern" 
                        value="<?php echo isset($settings['pointEarningRate']) ? $settings['pointEarningRate'] : '1.0'; ?>" 
                        required>
                    <small class="text-muted">Multiplier for point earning (1.0 = standard rate)</small>
                </div>
            </div>
            
            <div class="row">
                <div class="col-md-6 mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="pointsExpiryEnabled" id="pointsExpiryEnabled" 
                            <?php echo (isset($settings['pointsExpiryEnabled']) && $settings['pointsExpiryEnabled']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="pointsExpiryEnabled">
                            <strong>Enable Points Expiry</strong>
                        </label>
                    </div>
                    <small class="text-muted">Allow points to expire after a certain period</small>
                </div>
                <div class="col-md-6 mb-3" id="expiryDaysContainer" style="<?php echo (isset($settings['pointsExpiryEnabled']) && $settings['pointsExpiryEnabled']) ? '' : 'display: none;'; ?>">
                    <label class="form-label-modern">Points Expiry Days</label>
                    <input type="number" step="1" min="1" name="pointsExpiryDays" 
                        class="form-control form-control-modern" 
                        value="<?php echo isset($settings['pointsExpiryDays']) ? $settings['pointsExpiryDays'] : '365'; ?>">
                    <small class="text-muted">Number of days before points expire</small>
                </div>
            </div>
            
            <div class="text-end">
                <button type="submit" class="btn btn-submit-modern">
                    <i class="fa-solid fa-save"></i> Save Settings
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Tier Thresholds -->
<div class="form-card-modern">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fa-solid fa-trophy text-primary"></i> Tier Thresholds
        </h5>
    </div>
    <div class="card-body">
        <form id="tiersForm" method="post" action="<?php echo base_url('loyalty/updateTiers'); ?>">
            <div class="info-box">
                <i class="fa-solid fa-info-circle"></i>
                <strong>Note:</strong> Tiers are based on total lifetime points. Customers automatically advance to higher tiers when they reach the threshold.
            </div>
            
            <?php 
            $defaultTiers = array(
                'bronze' => array('name' => 'Bronze', 'threshold' => 0, 'benefits' => 'Standard rewards', 'enabled' => true),
                'silver' => array('name' => 'Silver', 'threshold' => 500, 'benefits' => '5% bonus points', 'enabled' => true),
                'gold' => array('name' => 'Gold', 'threshold' => 1000, 'benefits' => '10% bonus points', 'enabled' => true),
                'platinum' => array('name' => 'Platinum', 'threshold' => 2500, 'benefits' => '15% bonus points', 'enabled' => true)
            );
            $tiers = isset($settings['tiers']) ? $settings['tiers'] : $defaultTiers;
            foreach ($tiers as $tierKey => $tier): 
            ?>
            <div class="row mb-3">
                <div class="col-md-12">
                    <div class="d-flex align-items-center mb-2">
                        <span class="tier-badge <?php echo $tierKey; ?>"><?php echo htmlspecialchars($tier['name']); ?></span>
                        <div class="form-check form-switch ms-auto">
                            <input class="form-check-input" type="checkbox" 
                                name="tiers[<?php echo $tierKey; ?>][enabled]" 
                                id="tier_<?php echo $tierKey; ?>_enabled"
                                <?php echo (isset($tier['enabled']) && $tier['enabled']) ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="tier_<?php echo $tierKey; ?>_enabled">Enabled</label>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <label class="form-label-modern">Tier Name</label>
                    <input type="text" name="tiers[<?php echo $tierKey; ?>][name]" 
                        class="form-control form-control-modern" 
                        value="<?php echo htmlspecialchars($tier['name']); ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label-modern">Points Threshold</label>
                    <input type="number" step="1" min="0" name="tiers[<?php echo $tierKey; ?>][threshold]" 
                        class="form-control form-control-modern" 
                        value="<?php echo isset($tier['threshold']) ? $tier['threshold'] : 0; ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label-modern">Benefits</label>
                    <input type="text" name="tiers[<?php echo $tierKey; ?>][benefits]" 
                        class="form-control form-control-modern" 
                        value="<?php echo htmlspecialchars($tier['benefits']); ?>" required>
                </div>
            </div>
            <?php endforeach; ?>
            
            <div class="text-end">
                <button type="submit" class="btn btn-submit-modern">
                    <i class="fa-solid fa-save"></i> Save Tiers
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Rewards Management -->
<div class="form-card-modern">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fa-solid fa-gift text-primary"></i> Rewards Management
        </h5>
        <button type="button" class="btn btn-sm btn-submit-modern" data-bs-toggle="modal" data-bs-target="#rewardModal" onclick="openRewardModal()">
            <i class="fa-solid fa-plus"></i> Add Reward
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($rewards)): ?>
            <div class="text-center py-4">
                <i class="fa-solid fa-gift fa-3x text-muted mb-3"></i>
                <p class="text-muted">No rewards configured yet. Add your first reward above.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Points Required</th>
                            <th>Discount</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rewards as $rewardId => $reward): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($reward['name']); ?></strong></td>
                            <td><?php echo isset($reward['pointsRequired']) ? $reward['pointsRequired'] : 0; ?> points</td>
                            <td>
                                <?php 
                                if (isset($reward['discountType']) && $reward['discountType'] == 'percentage') {
                                    echo $reward['discountValue'] . '%';
                                } else {
                                    echo '$' . number_format($reward['discountValue'], 2);
                                }
                                ?>
                            </td>
                            <td>
                                <?php if (isset($reward['enabled']) && $reward['enabled']): ?>
                                    <span class="badge bg-success">Enabled</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Disabled</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-primary" onclick="editReward('<?php echo $rewardId; ?>', <?php echo htmlspecialchars(json_encode($reward)); ?>)">
                                    <i class="fa-solid fa-edit"></i> Edit
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="deleteReward('<?php echo $rewardId; ?>')">
                                    <i class="fa-solid fa-trash"></i> Delete
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Birthday Bonus -->
<div class="form-card-modern">
    <div class="card-header">
        <h5 class="mb-0">
            <i class="fa-solid fa-birthday-cake text-primary"></i> Birthday Bonus Points
        </h5>
    </div>
    <div class="card-body">
        <form id="birthdayForm" method="post" action="<?php echo base_url('loyalty/updateSettings'); ?>">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="birthdayBonusEnabled" id="birthdayBonusEnabled" 
                            <?php echo (isset($settings['birthdayBonusEnabled']) && $settings['birthdayBonusEnabled']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="birthdayBonusEnabled">
                            <strong>Enable Birthday Bonus</strong>
                        </label>
                    </div>
                    <small class="text-muted">Automatically award bonus points on customer birthdays</small>
                </div>
                <div class="col-md-6 mb-3" id="birthdayPointsContainer" style="<?php echo (isset($settings['birthdayBonusEnabled']) && $settings['birthdayBonusEnabled']) ? '' : 'display: none;'; ?>">
                    <label class="form-label-modern">Birthday Bonus Points</label>
                    <input type="number" step="1" min="0" name="birthdayBonusPoints" 
                        class="form-control form-control-modern" 
                        value="<?php echo isset($settings['birthdayBonusPoints']) ? $settings['birthdayBonusPoints'] : '100'; ?>">
                    <small class="text-muted">Points awarded on customer's birthday</small>
                </div>
            </div>
            <div class="text-end">
                <button type="submit" class="btn btn-submit-modern">
                    <i class="fa-solid fa-save"></i> Save Birthday Settings
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Double Points Days -->
<div class="form-card-modern">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fa-solid fa-calendar-star text-primary"></i> Double Points Days
        </h5>
        <button type="button" class="btn btn-sm btn-submit-modern" data-bs-toggle="modal" data-bs-target="#doublePointsModal" onclick="openDoublePointsModal()">
            <i class="fa-solid fa-plus"></i> Add Double Points Day
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($doublePointsDays)): ?>
            <div class="text-center py-4">
                <i class="fa-solid fa-calendar fa-3x text-muted mb-3"></i>
                <p class="text-muted">No double points days configured yet.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Multiplier</th>
                            <th>Description</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($doublePointsDays as $dayId => $day): ?>
                        <tr>
                            <td><?php echo date('M d, Y', $day['date'] / 1000); ?></td>
                            <td><strong><?php echo $day['multiplier']; ?>x</strong></td>
                            <td><?php echo htmlspecialchars($day['description']); ?></td>
                            <td>
                                <?php if (isset($day['enabled']) && $day['enabled']): ?>
                                    <span class="badge bg-success">Enabled</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Disabled</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="deleteDoublePointsDay('<?php echo $dayId; ?>')">
                                    <i class="fa-solid fa-trash"></i> Delete
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- VIP Promotions -->
<div class="form-card-modern">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fa-solid fa-crown text-primary"></i> VIP-Only Promotions
        </h5>
        <button type="button" class="btn btn-sm btn-submit-modern" data-bs-toggle="modal" data-bs-target="#vipPromoModal" onclick="openVIPPromoModal()">
            <i class="fa-solid fa-plus"></i> Add VIP Promotion
        </button>
    </div>
    <div class="card-body">
        <?php if (empty($vipPromotions)): ?>
            <div class="text-center py-4">
                <i class="fa-solid fa-crown fa-3x text-muted mb-3"></i>
                <p class="text-muted">No VIP promotions configured yet.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Tier Required</th>
                            <th>Points Multiplier</th>
                            <th>Date Range</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($vipPromotions as $promoId => $promo): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($promo['title']); ?></strong></td>
                            <td><span class="tier-badge <?php echo $promo['tierRequired']; ?>"><?php echo ucfirst($promo['tierRequired']); ?></span></td>
                            <td><strong><?php echo $promo['pointsMultiplier']; ?>x</strong></td>
                            <td>
                                <?php echo date('M d, Y', $promo['startDate'] / 1000); ?> - 
                                <?php echo date('M d, Y', $promo['endDate'] / 1000); ?>
                            </td>
                            <td>
                                <?php if (isset($promo['enabled']) && $promo['enabled']): ?>
                                    <span class="badge bg-success">Enabled</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Disabled</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-danger" onclick="deleteVIPPromotion('<?php echo $promoId; ?>')">
                                    <i class="fa-solid fa-trash"></i> Delete
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Reward Modal -->
<div class="modal fade" id="rewardModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add/Edit Reward</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="rewardForm" method="post" action="<?php echo base_url('loyalty/saveReward'); ?>">
                <div class="modal-body">
                    <input type="hidden" name="rewardId" id="rewardId">
                    <div class="mb-3">
                        <label class="form-label-modern">Reward Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="rewardName" class="form-control form-control-modern" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label-modern">Description</label>
                        <textarea name="description" id="rewardDescription" class="form-control form-control-modern" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label-modern">Points Required <span class="text-danger">*</span></label>
                        <input type="number" step="1" min="1" name="pointsRequired" id="rewardPointsRequired" class="form-control form-control-modern" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">Discount Type <span class="text-danger">*</span></label>
                            <select name="discountType" id="rewardDiscountType" class="form-control form-control-modern" required>
                                <option value="percentage">Percentage (%)</option>
                                <option value="fixed">Fixed Amount ($)</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">Discount Value <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" min="0" name="discountValue" id="rewardDiscountValue" class="form-control form-control-modern" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="enabled" id="rewardEnabled" checked>
                            <label class="form-check-label" for="rewardEnabled">Enabled</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-submit-modern">Save Reward</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Double Points Day Modal -->
<div class="modal fade" id="doublePointsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Double Points Day</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="doublePointsForm" method="post" action="<?php echo base_url('loyalty/addDoublePointsDay'); ?>">
                <div class="modal-body">
                    <input type="hidden" name="dayId" id="doublePointsDayId">
                    <div class="mb-3">
                        <label class="form-label-modern">Date <span class="text-danger">*</span></label>
                        <input type="date" name="date" id="doublePointsDate" class="form-control form-control-modern" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label-modern">Points Multiplier <span class="text-danger">*</span></label>
                        <input type="number" step="0.1" min="1" name="multiplier" id="doublePointsMultiplier" class="form-control form-control-modern" value="2.0" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label-modern">Description</label>
                        <textarea name="description" id="doublePointsDescription" class="form-control form-control-modern" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="enabled" id="doublePointsEnabled" checked>
                            <label class="form-check-label" for="doublePointsEnabled">Enabled</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-submit-modern">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- VIP Promotion Modal -->
<div class="modal fade" id="vipPromoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add VIP Promotion</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="vipPromoForm" method="post" action="<?php echo base_url('loyalty/addVIPPromotion'); ?>">
                <div class="modal-body">
                    <input type="hidden" name="promoId" id="vipPromoId">
                    <div class="mb-3">
                        <label class="form-label-modern">Title <span class="text-danger">*</span></label>
                        <input type="text" name="title" id="vipPromoTitle" class="form-control form-control-modern" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label-modern">Description</label>
                        <textarea name="description" id="vipPromoDescription" class="form-control form-control-modern" rows="3"></textarea>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">Tier Required <span class="text-danger">*</span></label>
                            <select name="tierRequired" id="vipPromoTierRequired" class="form-control form-control-modern" required>
                                <option value="silver">Silver</option>
                                <option value="gold">Gold</option>
                                <option value="platinum">Platinum</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">Points Multiplier <span class="text-danger">*</span></label>
                            <input type="number" step="0.1" min="1" name="pointsMultiplier" id="vipPromoMultiplier" class="form-control form-control-modern" value="1.5" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">Start Date <span class="text-danger">*</span></label>
                            <input type="date" name="startDate" id="vipPromoStartDate" class="form-control form-control-modern" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label-modern">End Date <span class="text-danger">*</span></label>
                            <input type="date" name="endDate" id="vipPromoEndDate" class="form-control form-control-modern" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="enabled" id="vipPromoEnabled" checked>
                            <label class="form-check-label" for="vipPromoEnabled">Enabled</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-submit-modern">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="<?php echo base_url('assets/js/jquery.min.js'); ?>"></script>
<script>
$(document).ready(function() {
    // Toggle expiry days
    $('#pointsExpiryEnabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#expiryDaysContainer').slideDown();
        } else {
            $('#expiryDaysContainer').slideUp();
        }
    });
    
    // Toggle birthday points
    $('#birthdayBonusEnabled').on('change', function() {
        if ($(this).is(':checked')) {
            $('#birthdayPointsContainer').slideDown();
        } else {
            $('#birthdayPointsContainer').slideUp();
        }
    });
    
    // Form submissions
    $('#settingsForm, #tiersForm, #birthdayForm').on('submit', function(e) {
        e.preventDefault();
        submitForm($(this));
    });
    
    $('#rewardForm, #doublePointsForm, #vipPromoForm').on('submit', function(e) {
        e.preventDefault();
        submitForm($(this), function() {
            $('#rewardModal, #doublePointsModal, #vipPromoModal').modal('hide');
            location.reload();
        });
    });
});

function submitForm(form, callback) {
    var formData = form.serialize();
    var url = form.attr('action');
    var submitBtn = form.find('button[type="submit"]');
    var originalText = submitBtn.html();
    submitBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
    
    $.ajax({
        url: url,
        type: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            submitBtn.prop('disabled', false).html(originalText);
            
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message,
                    confirmButtonText: 'OK',
                    timer: 2000
                }).then(function() {
                    if (callback) callback();
                    else if (!form.attr('id').includes('Modal')) location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: response.message,
                    confirmButtonText: 'OK'
                });
            }
        },
        error: function() {
            submitBtn.prop('disabled', false).html(originalText);
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Something went wrong. Please try again.',
                confirmButtonText: 'OK'
            });
        }
    });
}

function openRewardModal() {
    $('#rewardForm')[0].reset();
    $('#rewardId').val('');
}

function editReward(rewardId, reward) {
    $('#rewardId').val(rewardId);
    $('#rewardName').val(reward.name || '');
    $('#rewardDescription').val(reward.description || '');
    $('#rewardPointsRequired').val(reward.pointsRequired || 0);
    $('#rewardDiscountType').val(reward.discountType || 'percentage');
    $('#rewardDiscountValue').val(reward.discountValue || 0);
    $('#rewardEnabled').prop('checked', reward.enabled !== false);
    $('#rewardModal').modal('show');
}

function deleteReward(rewardId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This reward will be deleted permanently!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#72A565',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?php echo base_url('loyalty/deleteReward/'); ?>' + rewardId,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Deleted!', response.message, 'success').then(function() {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        }
    });
}

function openDoublePointsModal() {
    $('#doublePointsForm')[0].reset();
    $('#doublePointsDayId').val('');
    $('#doublePointsDate').val(new Date().toISOString().split('T')[0]);
}

function deleteDoublePointsDay(dayId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This double points day will be deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#72A565',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?php echo base_url('loyalty/deleteDoublePointsDay/'); ?>' + dayId,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Deleted!', response.message, 'success').then(function() {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        }
    });
}

function openVIPPromoModal() {
    $('#vipPromoForm')[0].reset();
    $('#vipPromoId').val('');
    var today = new Date().toISOString().split('T')[0];
    $('#vipPromoStartDate').val(today);
    var nextWeek = new Date();
    nextWeek.setDate(nextWeek.getDate() + 7);
    $('#vipPromoEndDate').val(nextWeek.toISOString().split('T')[0]);
}

function deleteVIPPromotion(promoId) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This VIP promotion will be deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#72A565',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?php echo base_url('loyalty/deleteVIPPromotion/'); ?>' + promoId,
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire('Deleted!', response.message, 'success').then(function() {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        }
    });
}
</script>
