<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin or instructor
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin' && $currentUser['role'] !== 'instructor') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_course_pricing'])) {
        // Update course pricing
        $courseId = (int)$_POST['course_id'];
        $price = (float)$_POST['price'];
        $currency = trim($_POST['currency']);
        $isFree = isset($_POST['is_free']) ? 1 : 0;

        // Check if user can edit this course
        if ($currentUser['role'] !== 'admin') {
            $stmt = $db->prepare("SELECT instructor_id FROM courses WHERE id = ?");
            $stmt->execute([$courseId]);
            $course = $stmt->fetch();
            if (!$course || $course['instructor_id'] != $currentUser['id']) {
                $error = 'You do not have permission to edit this course.';
            }
        }

        if (!$error) {
            $stmt = $db->prepare("
                UPDATE courses
                SET price = ?, currency = ?, is_free = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$isFree ? 0 : $price, $currency, $isFree, $courseId]);

            $success = 'Course pricing updated successfully!';
        }

    } elseif (isset($_POST['create_discount'])) {
        // Create new discount code
        $code = strtoupper(trim($_POST['code']));
        $description = trim($_POST['description']);
        $discountType = $_POST['discount_type'];
        $discountValue = (float)$_POST['discount_value'];
        $minPurchase = (float)$_POST['min_purchase'];
        $usageLimit = (int)$_POST['usage_limit'] ?: null;
        $validFrom = !empty($_POST['valid_from']) ? $_POST['valid_from'] : null;
        $validUntil = !empty($_POST['valid_until']) ? $_POST['valid_until'] : null;

        // Server-side validation
        if (empty($code)) {
            $error = 'Discount code is required.';
        } elseif (empty($description)) {
            $error = 'Description is required.';
        } elseif ($discountValue < 0) {
            $error = 'Discount value must be positive.';
        } elseif ($discountType === 'percentage' && $discountValue > 100) {
            $error = 'Percentage discount cannot exceed 100%.';
        } else {
            try {
                $stmt = $db->prepare("
                    INSERT INTO discount_codes
                    (code, description, discount_type, discount_value, min_purchase_amount,
                     usage_limit, valid_from, valid_until, is_active, created_by, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())
                ");
                $stmt->execute([
                    $code, $description, $discountType, $discountValue, $minPurchase,
                    $usageLimit, $validFrom, $validUntil, $currentUser['id']
                ]);

                $success = 'Discount code created successfully!';

            } catch (PDOException $e) {
                if ($e->getCode() == 23000) { // Duplicate entry
                    $error = 'Discount code already exists.';
                } else {
                    $error = 'Error creating discount code: ' . $e->getMessage();
                }
            }
        }

    } elseif (isset($_POST['update_discount'])) {
        // Update discount code
        $discountId = (int)$_POST['discount_id'];
        $code = strtoupper(trim($_POST['code']));
        $description = trim($_POST['description']);
        $discountType = $_POST['discount_type'];
        $discountValue = (float)$_POST['discount_value'];
        $minPurchase = (float)$_POST['min_purchase'];
        $usageLimit = (int)$_POST['usage_limit'] ?: null;
        $validFrom = !empty($_POST['valid_from']) ? $_POST['valid_from'] : null;
        $validUntil = !empty($_POST['valid_until']) ? $_POST['valid_until'] : null;
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        // Server-side validation
        if (empty($code)) {
            $error = 'Discount code is required.';
        } elseif (empty($description)) {
            $error = 'Description is required.';
        } elseif ($discountValue < 0) {
            $error = 'Discount value must be positive.';
        } elseif ($discountType === 'percentage' && $discountValue > 100) {
            $error = 'Percentage discount cannot exceed 100%.';
        } else {
            try {
                $stmt = $db->prepare("
                    UPDATE discount_codes
                    SET code = ?, description = ?, discount_type = ?, discount_value = ?,
                        min_purchase_amount = ?, usage_limit = ?, valid_from = ?,
                        valid_until = ?, is_active = ?, updated_at = NOW()
                    WHERE id = ?
                ");
                $stmt->execute([
                    $code, $description, $discountType, $discountValue, $minPurchase,
                    $usageLimit, $validFrom, $validUntil, $isActive, $discountId
                ]);

                $success = 'Discount code updated successfully!';

            } catch (PDOException $e) {
                if ($e->getCode() == 23000) { // Duplicate entry
                    $error = 'Discount code already exists.';
                } else {
                    $error = 'Error updating discount code: ' . $e->getMessage();
                }
            }
        }

    } elseif (isset($_POST['delete_discount'])) {
        // Delete discount code
        $discountId = (int)$_POST['discount_id'];

        $stmt = $db->prepare("DELETE FROM discount_codes WHERE id = ?");
        $stmt->execute([$discountId]);

        $success = 'Discount code deleted successfully!';
    }
}

// Get courses for pricing management
$query = "SELECT c.*, cat.name as category_name, u.username as instructor_name
          FROM courses c
          LEFT JOIN course_categories cat ON c.category_id = cat.id
          LEFT JOIN users u ON c.instructor_id = u.id";

if ($currentUser['role'] !== 'admin') {
    $query .= " WHERE c.instructor_id = ?";
    $stmt = $db->prepare($query);
    $stmt->execute([$currentUser['id']]);
} else {
    $stmt = $db->query($query);
}

$courses = $stmt->fetchAll();

// Get discount codes
$discounts = $db->query("
    SELECT d.*, u.username as created_by_name
    FROM discount_codes d
    LEFT JOIN users u ON d.created_by = u.id
    ORDER BY d.created_at DESC
")->fetchAll();

$page_title = 'Course Pricing Management';
include 'includes/admin_header.php';
?>

<!-- Custom Styles for Course Pricing Page -->
<style>
    :root {
        --primary-color: #1E3A8A;
        --primary-light: #3B82F6;
        --primary-dark: #1E40AF;
        --success-color: #059669;
        --success-light: #D1FAE5;
        --warning-color: #D97706;
        --warning-light: #FEF3C7;
        --danger-color: #DC2626;
        --danger-light: #FEE2E2;
        --info-color: #0284C7;
        --info-light: #E0F2FE;
        --gray-50: #F9FAFB;
        --gray-100: #F3F4F6;
        --gray-200: #E5E7EB;
        --gray-300: #D1D5DB;
        --gray-400: #9CA3AF;
        --gray-500: #6B7280;
        --gray-600: #4B5563;
        --gray-700: #374151;
        --gray-800: #1F2937;
        --gray-900: #111827;
        --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
        --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        --shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        --radius-sm: 0.375rem;
        --radius-md: 0.5rem;
        --radius-lg: 0.75rem;
        --radius-xl: 1rem;
        --transition-fast: 150ms ease;
        --transition-normal: 250ms ease;
        --transition-slow: 350ms ease;
    }

    .course-pricing-page {
        background: var(--gray-50);
        min-height: calc(100vh - 120px);
        padding-bottom: 2rem;
    }

    /* Page Header */
    .pricing-header-section {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
        padding: 2rem;
        border-radius: var(--radius-xl);
        margin-bottom: 1.5rem;
        color: white;
        position: relative;
        overflow: hidden;
    }

    .pricing-header-section::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -10%;
        width: 300px;
        height: 300px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
        pointer-events: none;
    }

    .pricing-header-section::after {
        content: '';
        position: absolute;
        bottom: -30%;
        left: 10%;
        width: 200px;
        height: 200px;
        background: rgba(255, 255, 255, 0.05);
        border-radius: 50%;
        pointer-events: none;
    }

    .pricing-header-content {
        position: relative;
        z-index: 1;
    }

    .pricing-header-title {
        font-size: 1.75rem;
        font-weight: 700;
        margin-bottom: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .pricing-header-title i {
        font-size: 1.5rem;
    }

    .pricing-header-subtitle {
        font-size: 0.95rem;
        opacity: 0.9;
        font-weight: 400;
    }

    /* Stats Cards */
    .pricing-stats-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 1rem;
        margin-bottom: 1.5rem;
    }

    @media (max-width: 1200px) {
        .pricing-stats-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 640px) {
        .pricing-stats-grid {
            grid-template-columns: 1fr;
        }
    }

    .stat-card-enterprise {
        background: white;
        border-radius: var(--radius-lg);
        padding: 1.25rem;
        display: flex;
        align-items: center;
        gap: 1rem;
        box-shadow: var(--shadow-sm);
        border: 1px solid var(--gray-200);
        transition: all var(--transition-normal);
    }

    .stat-card-enterprise:hover {
        transform: translateY(-2px);
        box-shadow: var(--shadow-md);
        border-color: var(--primary-light);
    }

    .stat-icon-container {
        width: 52px;
        height: 52px;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.25rem;
        flex-shrink: 0;
    }

    .stat-icon-container.primary {
        background: linear-gradient(135deg, #EEF2FF 0%, #E0E7FF 100%);
        color: var(--primary-color);
    }

    .stat-icon-container.success {
        background: linear-gradient(135deg, #ECFDF5 0%, #D1FAE5 100%);
        color: var(--success-color);
    }

    .stat-icon-container.warning {
        background: linear-gradient(135deg, #FFFBEB 0%, #FEF3C7 100%);
        color: var(--warning-color);
    }

    .stat-icon-container.info {
        background: linear-gradient(135deg, #F0F9FF 0%, #E0F2FE 100%);
        color: var(--info-color);
    }

    .stat-content-container {
        flex: 1;
        min-width: 0;
    }

    .stat-number-enterprise {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--gray-900);
        line-height: 1.2;
    }

    .stat-label-enterprise {
        font-size: 0.8rem;
        color: var(--gray-500);
        font-weight: 500;
        text-transform: uppercase;
        letter-spacing: 0.025em;
    }

    /* Alert Messages */
    .alert-container {
        margin-bottom: 1.5rem;
    }

    .alert-enterprise {
        padding: 1rem 1.25rem;
        border-radius: var(--radius-md);
        display: flex;
        align-items: center;
        gap: 0.75rem;
        font-size: 0.9rem;
        font-weight: 500;
        border: 1px solid transparent;
        animation: slideIn 0.3s ease;
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(-10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .alert-enterprise.success {
        background: var(--success-light);
        color: #065F46;
        border-color: #A7F3D0;
    }

    .alert-enterprise.success i {
        color: var(--success-color);
    }

    .alert-enterprise.danger {
        background: var(--danger-light);
        color: #991B1B;
        border-color: #FECACA;
    }

    .alert-enterprise.danger i {
        color: var(--danger-color);
    }

    .alert-close-btn {
        margin-left: auto;
        background: none;
        border: none;
        cursor: pointer;
        font-size: 1rem;
        opacity: 0.6;
        transition: opacity var(--transition-fast);
        padding: 0.25rem;
        color: inherit;
    }

    .alert-close-btn:hover {
        opacity: 1;
    }

    /* Content Sections */
    .pricing-section {
        background: white;
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-sm);
        border: 1px solid var(--gray-200);
        margin-bottom: 1.5rem;
        overflow: hidden;
    }

    .section-header {
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--gray-100);
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        flex-wrap: wrap;
        background: var(--gray-50);
    }

    .section-header-content {
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .section-icon {
        width: 36px;
        height: 36px;
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1rem;
    }

    .section-icon.courses {
        background: #EEF2FF;
        color: var(--primary-color);
    }

    .section-icon.discounts {
        background: #FEF3C7;
        color: var(--warning-color);
    }

    .section-title-group h3 {
        font-size: 1.1rem;
        font-weight: 600;
        color: var(--gray-900);
        margin: 0;
    }

    .section-title-group p {
        font-size: 0.8rem;
        color: var(--gray-500);
        margin: 0;
    }

    /* Buttons */
    .btn-enterprise {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        font-weight: 500;
        border-radius: var(--radius-md);
        border: none;
        cursor: pointer;
        transition: all var(--transition-fast);
        text-decoration: none;
    }

    .btn-enterprise:hover {
        transform: translateY(-1px);
    }

    .btn-enterprise:active {
        transform: translateY(0);
    }

    .btn-primary-enterprise {
        background: var(--primary-color);
        color: white;
        box-shadow: var(--shadow-sm);
    }

    .btn-primary-enterprise:hover {
        background: var(--primary-dark);
        box-shadow: var(--shadow-md);
    }

    .btn-secondary-enterprise {
        background: white;
        color: var(--gray-700);
        border: 1px solid var(--gray-300);
    }

    .btn-secondary-enterprise:hover {
        background: var(--gray-50);
        border-color: var(--gray-400);
    }

    .btn-success-enterprise {
        background: var(--success-color);
        color: white;
    }

    .btn-success-enterprise:hover {
        background: #047857;
    }

    .btn-danger-enterprise {
        background: var(--danger-color);
        color: white;
    }

    .btn-danger-enterprise:hover {
        background: #B91C1C;
    }

    .btn-sm-enterprise {
        padding: 0.375rem 0.75rem;
        font-size: 0.8rem;
    }

    /* Table Styles */
    .table-wrapper-enterprise {
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }

    .table-enterprise {
        width: 100%;
        border-collapse: collapse;
        font-size: 0.875rem;
    }

    .table-enterprise thead {
        background: var(--gray-50);
    }

    .table-enterprise th {
        padding: 0.875rem 1rem;
        text-align: left;
        font-weight: 600;
        color: var(--gray-600);
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        border-bottom: 1px solid var(--gray-200);
        white-space: nowrap;
    }

    .table-enterprise td {
        padding: 1rem;
        border-bottom: 1px solid var(--gray-100);
        vertical-align: middle;
    }

    .table-enterprise tbody tr {
        transition: background var(--transition-fast);
    }

    .table-enterprise tbody tr:hover {
        background: var(--gray-50);
    }

    .table-enterprise tbody tr:last-child td {
        border-bottom: none;
    }

    /* Course Info Cell */
    .course-cell {
        display: flex;
        flex-direction: column;
        gap: 0.25rem;
    }

    .course-title-cell {
        font-weight: 600;
        color: var(--gray-900);
    }

    .course-meta-cell {
        font-size: 0.75rem;
        color: var(--gray-400);
    }

    /* Badges */
    .badge-enterprise {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.375rem 0.625rem;
        border-radius: var(--radius-sm);
        font-size: 0.75rem;
        font-weight: 600;
    }

    .badge-free {
        background: var(--success-light);
        color: #065F46;
    }

    .badge-paid {
        background: #EEF2FF;
        color: var(--primary-color);
    }

    .badge-published {
        background: var(--success-light);
        color: #065F46;
    }

    .badge-draft {
        background: var(--warning-light);
        color: #92400E;
    }

    .badge-active {
        background: var(--success-light);
        color: #065F46;
    }

    .badge-inactive {
        background: var(--gray-100);
        color: var(--gray-500);
    }

    /* Discount Code */
    .discount-code-enterprise {
        font-family: 'Monaco', 'Menlo', monospace;
        font-size: 0.8rem;
        font-weight: 600;
        background: var(--gray-100);
        padding: 0.375rem 0.625rem;
        border-radius: var(--radius-sm);
        color: var(--gray-800);
        letter-spacing: 0.025em;
    }

    /* Discount Type */
    .discount-type-badge {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .discount-type-badge.percentage {
        color: var(--primary-color);
    }

    .discount-type-badge.fixed_amount {
        color: var(--success-color);
    }

    /* Usage Info */
    .usage-info-cell {
        display: flex;
        align-items: center;
        gap: 0.25rem;
    }

    .usage-count-cell {
        font-weight: 600;
        color: var(--gray-900);
    }

    .usage-limit-cell {
        color: var(--gray-400);
        font-size: 0.8rem;
    }

    .usage-unlimited-cell {
        color: var(--gray-400);
        font-size: 0.8rem;
        font-style: italic;
    }

    /* Date Cell */
    .date-cell {
        font-size: 0.85rem;
        color: var(--gray-600);
    }

    .date-unlimited-cell {
        color: var(--gray-400);
        font-style: italic;
        font-size: 0.8rem;
    }

    /* Action Buttons */
    .action-buttons-group {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
    }

    .btn-action-edit {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.375rem 0.75rem;
        font-size: 0.8rem;
        font-weight: 500;
        border-radius: var(--radius-sm);
        border: 1px solid var(--gray-200);
        background: white;
        color: var(--gray-700);
        cursor: pointer;
        transition: all var(--transition-fast);
    }

    .btn-action-edit:hover {
        background: var(--gray-50);
        border-color: var(--primary-color);
        color: var(--primary-color);
    }

    .btn-action-delete {
        display: inline-flex;
        align-items: center;
        gap: 0.375rem;
        padding: 0.375rem 0.75rem;
        font-size: 0.8rem;
        font-weight: 500;
        border-radius: var(--radius-sm);
        border: 1px solid var(--gray-200);
        background: white;
        color: var(--danger-color);
        cursor: pointer;
        transition: all var(--transition-fast);
    }

    .btn-action-delete:hover {
        background: var(--danger-light);
        border-color: var(--danger-color);
        color: var(--danger-color);
    }

    /* Empty State */
    .empty-state-enterprise {
        text-align: center;
        padding: 3rem 1.5rem;
    }

    .empty-state-icon-enterprise {
        width: 64px;
        height: 64px;
        margin: 0 auto 1rem;
        background: var(--gray-100);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.5rem;
        color: var(--gray-400);
    }

    .empty-state-title {
        font-size: 1rem;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
    }

    .empty-state-text {
        font-size: 0.875rem;
        color: var(--gray-500);
        max-width: 400px;
        margin: 0 auto;
    }

    /* Modal Styles */
    .modal-backdrop-enterprise {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        display: none;
        opacity: 0;
        transition: opacity var(--transition-normal);
    }

    .modal-backdrop-enterprise.show {
        display: block;
        opacity: 1;
    }

    .modal-enterprise {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%) scale(0.95);
        background: white;
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-xl);
        z-index: 1001;
        width: 90%;
        max-width: 500px;
        max-height: 90vh;
        overflow-y: auto;
        display: none;
        opacity: 0;
        transition: all var(--transition-normal);
    }

    .modal-enterprise.show {
        display: block;
        opacity: 1;
        transform: translate(-50%, -50%) scale(1);
    }

    .modal-enterprise-lg {
        max-width: 600px;
    }

    .modal-header-enterprise {
        padding: 1.25rem 1.5rem;
        border-bottom: 1px solid var(--gray-200);
        display: flex;
        align-items: center;
        justify-content: space-between;
        background: var(--gray-50);
        border-radius: var(--radius-lg) var(--radius-lg) 0 0;
    }

    .modal-title-enterprise {
        font-size: 1.125rem;
        font-weight: 600;
        color: var(--gray-900);
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .modal-close-enterprise {
        width: 32px;
        height: 32px;
        border: none;
        background: transparent;
        cursor: pointer;
        border-radius: var(--radius-sm);
        display: flex;
        align-items: center;
        justify-content: center;
        color: var(--gray-500);
        transition: all var(--transition-fast);
    }

    .modal-close-enterprise:hover {
        background: var(--gray-200);
        color: var(--gray-700);
    }

    .modal-body-enterprise {
        padding: 1.5rem;
    }

    .modal-footer-enterprise {
        padding: 1rem 1.5rem;
        border-top: 1px solid var(--gray-200);
        display: flex;
        justify-content: flex-end;
        gap: 0.75rem;
        background: var(--gray-50);
        border-radius: 0 0 var(--radius-lg) var(--radius-lg);
    }

    /* Form Styles */
    .form-group-enterprise {
        margin-bottom: 1.25rem;
    }

    .form-label-enterprise {
        display: block;
        font-size: 0.875rem;
        font-weight: 600;
        color: var(--gray-700);
        margin-bottom: 0.5rem;
    }

    .form-label-required::after {
        content: '*';
        color: var(--danger-color);
        margin-left: 0.25rem;
    }

    .form-input-enterprise {
        width: 100%;
        padding: 0.625rem 0.875rem;
        font-size: 0.875rem;
        border: 1px solid var(--gray-300);
        border-radius: var(--radius-md);
        background: white;
        color: var(--gray-900);
        transition: all var(--transition-fast);
    }

    .form-input-enterprise:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(30, 58, 138, 0.1);
    }

    .form-input-enterprise:disabled {
        background: var(--gray-100);
        cursor: not-allowed;
    }

    .form-input-enterprise.error {
        border-color: var(--danger-color);
    }

    .form-input-enterprise::placeholder {
        color: var(--gray-400);
    }

    .form-select-enterprise {
        width: 100%;
        padding: 0.625rem 0.875rem;
        font-size: 0.875rem;
        border: 1px solid var(--gray-300);
        border-radius: var(--radius-md);
        background: white;
        color: var(--gray-900);
        transition: all var(--transition-fast);
        cursor: pointer;
    }

    .form-select-enterprise:focus {
        outline: none;
        border-color: var(--primary-color);
        box-shadow: 0 0 0 3px rgba(30, 58, 138, 0.1);
    }

    .form-help-text {
        font-size: 0.75rem;
        color: var(--gray-500);
        margin-top: 0.375rem;
    }

    .form-error-text {
        font-size: 0.75rem;
        color: var(--danger-color);
        margin-top: 0.375rem;
        display: none;
    }

    .form-row-enterprise {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }

    @media (max-width: 640px) {
        .form-row-enterprise {
            grid-template-columns: 1fr;
        }
    }

    /* Checkbox Styles */
    .checkbox-wrapper-enterprise {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        cursor: pointer;
    }

    .checkbox-input-enterprise {
        width: 18px;
        height: 18px;
        border: 2px solid var(--gray-300);
        border-radius: var(--radius-sm);
        cursor: pointer;
        transition: all var(--transition-fast);
        accent-color: var(--primary-color);
    }

    .checkbox-input-enterprise:checked {
        background: var(--primary-color);
        border-color: var(--primary-color);
    }

    .checkbox-label-enterprise {
        font-size: 0.875rem;
        color: var(--gray-700);
        user-select: none;
    }

    /* Input Group */
    .input-group-enterprise {
        display: flex;
    }

    .input-group-prepend {
        display: flex;
    }

    .input-group-text-enterprise {
        padding: 0.625rem 0.875rem;
        background: var(--gray-100);
        border: 1px solid var(--gray-300);
        border-right: none;
        border-radius: var(--radius-md) 0 0 var(--radius-md);
        color: var(--gray-500);
        font-size: 0.875rem;
        font-weight: 500;
    }

    .input-group-enterprise .form-input-enterprise {
        border-radius: 0 var(--radius-md) var(--radius-md) 0;
        flex: 1;
    }

    .input-group-select .input-group-text-enterprise {
        border-right: 1px solid var(--gray-300);
        border-radius: var(--radius-md) 0 0 var(--radius-md);
    }

    .input-group-select .form-select-enterprise {
        border-radius: 0 var(--radius-md) var(--radius-md) 0;
    }

    /* Loading Spinner */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(255, 255, 255, 0.9);
        display: none;
        align-items: center;
        justify-content: center;
        z-index: 9999;
    }

    .loading-overlay.show {
        display: flex;
    }

    .loading-spinner {
        width: 40px;
        height: 40px;
        border: 3px solid var(--gray-200);
        border-top-color: var(--primary-color);
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
    }

    @keyframes spin {
        to {
            transform: rotate(360deg);
        }
    }

    /* Responsive Table Scroll */
    @media (max-width: 1024px) {
        .table-enterprise {
            font-size: 0.8rem;
        }

        .table-enterprise th,
        .table-enterprise td {
            padding: 0.75rem;
        }
    }

    @media (max-width: 768px) {
        .section-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .pricing-header-title {
            font-size: 1.25rem;
        }

        .action-buttons-group {
            width: 100%;
        }

        .btn-action-edit,
        .btn-action-delete {
            flex: 1;
            justify-content: center;
        }
    }

    /* Tooltip */
    .tooltip-enterprise {
        position: relative;
    }

    .tooltip-enterprise::after {
        content: attr(data-tooltip);
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        background: var(--gray-800);
        color: white;
        padding: 0.375rem 0.625rem;
        border-radius: var(--radius-sm);
        font-size: 0.75rem;
        white-space: nowrap;
        opacity: 0;
        visibility: hidden;
        transition: all var(--transition-fast);
        z-index: 100;
    }

    .tooltip-enterprise:hover::after {
        opacity: 1;
        visibility: visible;
    }

    /* Keyboard Focus Styles */
    .btn-enterprise:focus,
    .form-input-enterprise:focus,
    .form-select-enterprise:focus,
    .checkbox-input-enterprise:focus {
        outline: 2px solid var(--primary-light);
        outline-offset: 2px;
    }

    /* Animation for modals */
    @keyframes modalFadeIn {
        from {
            opacity: 0;
            transform: translate(-50%, -50%) scale(0.95);
        }
        to {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
        }
    }

    .modal-enterprise.show {
        animation: modalFadeIn 0.25s ease-out;
    }

    /* Transition for price fields */
    .price-fields-container {
        transition: all var(--transition-normal);
    }

    .price-fields-container.hidden {
        display: none;
        opacity: 0;
    }

    /* Highlight animation for success */
    @keyframes highlight-success {
        0% {
            background-color: var(--success-light);
        }
        100% {
            background-color: transparent;
        }
    }

    .row-highlight {
        animation: highlight-success 2s ease-out;
    }
</style>

<div class="course-pricing-page">
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay" role="alert" aria-live="assertive">
        <div class="loading-spinner"></div>
    </div>

    <!-- Header Section -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-4">
        <div class="pricing-header-section">
            <div class="pricing-header-content">
                <h1 class="pricing-header-title">
                    <i class="fas fa-dollar-sign"></i>
                    Course Pricing Management
                </h1>
                <p class="pricing-header-subtitle">
                    Configure course prices, manage discount codes, and control billing settings
                </p>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="pricing-stats-grid">
            <div class="stat-card-enterprise" role="region" aria-label="Total Courses">
                <div class="stat-icon-container primary">
                    <i class="fas fa-book-open"></i>
                </div>
                <div class="stat-content-container">
                    <div class="stat-number-enterprise"><?php echo count($courses); ?></div>
                    <div class="stat-label-enterprise">Total Courses</div>
                </div>
            </div>
            <div class="stat-card-enterprise" role="region" aria-label="Free Courses">
                <div class="stat-icon-container success">
                    <i class="fas fa-gift"></i>
                </div>
                <div class="stat-content-container">
                    <div class="stat-number-enterprise"><?php echo count(array_filter($courses, function($c) { return $c['is_free']; })); ?></div>
                    <div class="stat-label-enterprise">Free Courses</div>
                </div>
            </div>
            <div class="stat-card-enterprise" role="region" aria-label="Paid Courses">
                <div class="stat-icon-container warning">
                    <i class="fas fa-dollar-sign"></i>
                </div>
                <div class="stat-content-container">
                    <div class="stat-number-enterprise"><?php echo count(array_filter($courses, function($c) { return !$c['is_free']; })); ?></div>
                    <div class="stat-label-enterprise">Paid Courses</div>
                </div>
            </div>
            <div class="stat-card-enterprise" role="region" aria-label="Active Discounts">
                <div class="stat-icon-container info">
                    <i class="fas fa-tags"></i>
                </div>
                <div class="stat-content-container">
                    <div class="stat-number-enterprise"><?php echo count($discounts); ?></div>
                    <div class="stat-label-enterprise">Discount Codes</div>
                </div>
            </div>
        </div>

        <!-- Alert Messages -->
        <div class="alert-container">
            <?php if ($error): ?>
                <div class="alert-enterprise danger" role="alert">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?php echo htmlspecialchars($error); ?></span>
                    <button class="alert-close-btn" onclick="this.parentElement.remove()" aria-label="Close alert">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            <?php endif; ?>

            <?php if ($success): ?>
                <div class="alert-enterprise success" role="alert">
                    <i class="fas fa-check-circle"></i>
                    <span><?php echo htmlspecialchars($success); ?></span>
                    <button class="alert-close-btn" onclick="this.parentElement.remove()" aria-label="Close alert">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            <?php endif; ?>
        </div>

        <!-- Course Pricing Section -->
        <section class="pricing-section" aria-labelledby="course-pricing-heading">
            <div class="section-header">
                <div class="section-header-content">
                    <div class="section-icon courses">
                        <i class="fas fa-book"></i>
                    </div>
                    <div class="section-title-group">
                        <h3 id="course-pricing-heading">Course Pricing</h3>
                        <p>Manage pricing for all your courses</p>
                    </div>
                </div>
            </div>
            <div class="table-wrapper-enterprise">
                <table class="table-enterprise" role="table" aria-label="Course pricing table">
                    <thead>
                        <tr>
                            <th scope="col">Course</th>
                            <th scope="col">Category</th>
                            <th scope="col">Instructor</th>
                            <th scope="col">Price</th>
                            <th scope="col">Status</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($courses)): ?>
                            <tr>
                                <td colspan="6">
                                    <div class="empty-state-enterprise">
                                        <div class="empty-state-icon-enterprise">
                                            <i class="fas fa-book"></i>
                                        </div>
                                        <h4 class="empty-state-title">No Courses Found</h4>
                                        <p class="empty-state-text">No courses available for pricing management. Create a course first to configure its pricing.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($courses as $course): ?>
                                <tr>
                                    <td>
                                        <div class="course-cell">
                                            <span class="course-title-cell"><?php echo htmlspecialchars($course['title']); ?></span>
                                            <span class="course-meta-cell">ID: <?php echo $course['id']; ?></span>
                                        </div>
                                    </td>
                                    <td><?php echo htmlspecialchars($course['category_name'] ?? 'Uncategorized'); ?></td>
                                    <td><?php echo htmlspecialchars($course['instructor_name']); ?></td>
                                    <td>
                                        <?php if ($course['is_free']): ?>
                                            <span class="badge-enterprise badge-free">
                                                <i class="fas fa-gift"></i> Free
                                            </span>
                                        <?php else: ?>
                                            <span class="badge-enterprise badge-paid">
                                                <i class="fas fa-dollar-sign"></i>
                                                <?php echo htmlspecialchars($course['currency']); ?> <?php echo number_format($course['price'], 2); ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge-enterprise badge-<?php echo $course['status'] === 'published' ? 'published' : 'draft'; ?>">
                                            <i class="fas fa-<?php echo $course['status'] === 'published' ? 'check-circle' : 'clock'; ?>"></i>
                                            <?php echo ucfirst($course['status']); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-buttons-group">
                                            <button class="btn-action-edit" 
                                                    onclick="editCoursePricing(<?php echo $course['id']; ?>, '<?php echo addslashes($course['title']); ?>', <?php echo $course['price']; ?>, '<?php echo $course['currency']; ?>', <?php echo $course['is_free'] ? 'true' : 'false'; ?>)"
                                                    aria-label="Edit pricing for <?php echo htmlspecialchars($course['title']); ?>">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>

        <!-- Discount Codes Section -->
        <section class="pricing-section" aria-labelledby="discount-codes-heading">
            <div class="section-header">
                <div class="section-header-content">
                    <div class="section-icon discounts">
                        <i class="fas fa-percent"></i>
                    </div>
                    <div class="section-title-group">
                        <h3 id="discount-codes-heading">Discount Codes</h3>
                        <p>Manage promotional codes and special offers</p>
                    </div>
                </div>
                <button class="btn-enterprise btn-primary-enterprise" onclick="showCreateDiscountModal()" aria-haspopup="dialog">
                    <i class="fas fa-plus"></i> Create Code
                </button>
            </div>
            <div class="table-wrapper-enterprise">
                <table class="table-enterprise" role="table" aria-label="Discount codes table">
                    <thead>
                        <tr>
                            <th scope="col">Code</th>
                            <th scope="col">Description</th>
                            <th scope="col">Type</th>
                            <th scope="col">Value</th>
                            <th scope="col">Usage</th>
                            <th scope="col">Valid Until</th>
                            <th scope="col">Status</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($discounts)): ?>
                            <tr>
                                <td colspan="8">
                                    <div class="empty-state-enterprise">
                                        <div class="empty-state-icon-enterprise">
                                            <i class="fas fa-tags"></i>
                                        </div>
                                        <h4 class="empty-state-title">No Discount Codes</h4>
                                        <p class="empty-state-text">Create your first discount code to offer promotions to your students.</p>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($discounts as $discount): ?>
                                <tr>
                                    <td>
                                        <code class="discount-code-enterprise"><?php echo htmlspecialchars($discount['code']); ?></code>
                                    </td>
                                    <td><?php echo htmlspecialchars($discount['description']); ?></td>
                                    <td>
                                        <span class="discount-type-badge <?php echo $discount['discount_type']; ?>">
                                            <i class="fas fa-<?php echo $discount['discount_type'] === 'percentage' ? 'percent' : 'dollar-sign'; ?>"></i>
                                            <?php echo ucfirst(str_replace('_', ' ', $discount['discount_type'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <strong>
                                            <?php if ($discount['discount_type'] === 'percentage'): ?>
                                                <?php echo $discount['discount_value']; ?>%
                                            <?php else: ?>
                                                $<?php echo number_format($discount['discount_value'], 2); ?>
                                            <?php endif; ?>
                                        </strong>
                                    </td>
                                    <td>
                                        <div class="usage-info-cell">
                                            <span class="usage-count-cell"><?php echo $discount['usage_count']; ?></span>
                                            <?php if ($discount['usage_limit']): ?>
                                                <span class="usage-limit-cell">/ <?php echo $discount['usage_limit']; ?></span>
                                            <?php else: ?>
                                                <span class="usage-unlimited-cell">unlimited</span>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php if ($discount['valid_until']): ?>
                                            <span class="date-cell"><?php echo date('M j, Y', strtotime($discount['valid_until'])); ?></span>
                                        <?php else: ?>
                                            <span class="date-unlimited-cell">No expiry</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <span class="badge-enterprise badge-<?php echo $discount['is_active'] ? 'active' : 'inactive'; ?>">
                                            <i class="fas fa-<?php echo $discount['is_active'] ? 'check-circle' : 'pause-circle'; ?>"></i>
                                            <?php echo $discount['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="action-buttons-group">
                                            <button class="btn-action-edit" 
                                                    onclick="editDiscount(<?php echo htmlspecialchars(json_encode($discount)); ?>)"
                                                    aria-label="Edit discount code <?php echo htmlspecialchars($discount['code']); ?>">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <button class="btn-action-delete" 
                                                    onclick="deleteDiscount(<?php echo $discount['id']; ?>, '<?php echo addslashes($discount['code']); ?>')"
                                                    aria-label="Delete discount code <?php echo htmlspecialchars($discount['code']); ?>">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </section>
    </div>
</div>

<!-- Course Pricing Modal -->
<div class="modal-backdrop-enterprise" id="coursePricingModalBackdrop" onclick="closeCoursePricingModal()"></div>
<div class="modal-enterprise" id="coursePricingModal" role="dialog" aria-labelledby="coursePricingModalTitle" aria-modal="true">
    <div class="modal-header-enterprise">
        <h5 class="modal-title-enterprise" id="coursePricingModalTitle">
            <i class="fas fa-edit"></i> Edit Course Pricing
        </h5>
        <button class="modal-close-enterprise" onclick="closeCoursePricingModal()" aria-label="Close modal">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <form method="POST" id="coursePricingForm" onsubmit="showLoading()">
        <div class="modal-body-enterprise">
            <input type="hidden" name="course_id" id="course_id">
            <div class="form-group-enterprise">
                <label class="form-label-enterprise" for="course_title">Course</label>
                <input type="text" class="form-input-enterprise" id="course_title" readonly aria-readonly="true">
            </div>
            <div class="form-group-enterprise">
                <div class="checkbox-wrapper-enterprise">
                    <input class="checkbox-input-enterprise" type="checkbox" id="is_free" name="is_free" onchange="togglePriceFields()">
                    <label class="checkbox-label-enterprise" for="is_free">This course is free</label>
                </div>
            </div>
            <div class="form-group-enterprise price-fields-container" id="price_fields">
                <label for="price" class="form-label-enterprise form-label-required">Price</label>
                <div class="input-group-enterprise input-group-select">
                    <div class="input-group-prepend">
                        <span class="input-group-text-enterprise">
                            <i class="fas fa-dollar-sign"></i>
                        </span>
                    </div>
                    <select class="form-select-enterprise" name="currency" id="currency" style="max-width: 100px;" aria-label="Currency">
                        <option value="USD">USD</option>
                        <option value="EUR">EUR</option>
                        <option value="GBP">GBP</option>
                        <option value="ZAR">ZAR</option>
                    </select>
                    <input type="number" class="form-input-enterprise" name="price" id="price" step="0.01" min="0" placeholder="0.00" required aria-required="true">
                </div>
            </div>
        </div>
        <div class="modal-footer-enterprise">
            <button type="button" class="btn-enterprise btn-secondary-enterprise" onclick="closeCoursePricingModal()">Cancel</button>
            <button type="submit" name="update_course_pricing" class="btn-enterprise btn-primary-enterprise">
                <i class="fas fa-save"></i> Update Pricing
            </button>
        </div>
    </form>
</div>

<!-- Discount Modal -->
<div class="modal-backdrop-enterprise" id="discountModalBackdrop" onclick="closeDiscountModal()"></div>
<div class="modal-enterprise modal-enterprise-lg" id="discountModal" role="dialog" aria-labelledby="discountModalTitle" aria-modal="true">
    <div class="modal-header-enterprise">
        <h5 class="modal-title-enterprise" id="discountModalTitle">
            <i class="fas fa-tag"></i> Create Discount Code
        </h5>
        <button class="modal-close-enterprise" onclick="closeDiscountModal()" aria-label="Close modal">
            <i class="fas fa-times"></i>
        </button>
    </div>
    <form method="POST" id="discountForm" onsubmit="showLoading()">
        <div class="modal-body-enterprise">
            <input type="hidden" name="discount_id" id="discount_id">
            
            <div class="form-row-enterprise">
                <div class="form-group-enterprise">
                    <label for="code" class="form-label-enterprise form-label-required">Discount Code</label>
                    <input type="text" class="form-input-enterprise" name="code" id="code" required style="text-transform: uppercase;" 
                           pattern="[A-Z0-9]+" minlength="3" maxlength="20" aria-required="true"
                           placeholder="e.g., SAVE20">
                    <div class="form-help-text">Unique code (3-20 characters, letters and numbers only)</div>
                </div>
                <div class="form-group-enterprise">
                    <label for="discount_type" class="form-label-enterprise form-label-required">Discount Type</label>
                    <select class="form-select-enterprise" name="discount_type" id="discount_type" required onchange="updateValueHelp()" aria-required="true">
                        <option value="percentage">Percentage (%)</option>
                        <option value="fixed_amount">Fixed Amount ($)</option>
                    </select>
                </div>
            </div>

            <div class="form-group-enterprise">
                <label for="description" class="form-label-enterprise form-label-required">Description</label>
                <input type="text" class="form-input-enterprise" name="description" id="description" required 
                       placeholder="Enter a brief description" aria-required="true">
                <div class="form-help-text">Brief description of this discount (shown to students)</div>
            </div>

            <div class="form-row-enterprise">
                <div class="form-group-enterprise">
                    <label for="discount_value" class="form-label-enterprise form-label-required">Discount Value</label>
                    <input type="number" class="form-input-enterprise" name="discount_value" id="discount_value" 
                           step="0.01" min="0" max="100" required aria-required="true"
                           placeholder="0.00">
                    <div class="form-help-text" id="value_help">Percentage (0-100)</div>
                </div>
                <div class="form-group-enterprise">
                    <label for="min_purchase" class="form-label-enterprise">Minimum Purchase</label>
                    <div class="input-group-enterprise">
                        <div class="input-group-prepend">
                            <span class="input-group-text-enterprise">$</span>
                        </div>
                        <input type="number" class="form-input-enterprise" name="min_purchase" id="min_purchase" 
                               step="0.01" min="0" value="0" placeholder="0.00">
                    </div>
                    <div class="form-help-text">Minimum order amount to use this discount</div>
                </div>
            </div>

            <div class="form-row-enterprise">
                <div class="form-group-enterprise">
                    <label for="usage_limit" class="form-label-enterprise">Usage Limit</label>
                    <input type="number" class="form-input-enterprise" name="usage_limit" id="usage_limit" 
                           min="1" placeholder="Unlimited">
                    <div class="form-help-text">Leave empty for unlimited uses</div>
                </div>
                <div class="form-group-enterprise">
                    <label for="valid_from" class="form-label-enterprise">Valid From</label>
                    <input type="date" class="form-input-enterprise" name="valid_from" id="valid_from">
                </div>
            </div>

            <div class="form-group-enterprise">
                <label for="valid_until" class="form-label-enterprise">Valid Until</label>
                <input type="date" class="form-input-enterprise" name="valid_until" id="valid_until">
                <div class="form-help-text">Leave empty for no expiration date</div>
            </div>

            <div class="form-group-enterprise" id="active_field" style="display: none;">
                <div class="checkbox-wrapper-enterprise">
                    <input class="checkbox-input-enterprise" type="checkbox" id="is_active" name="is_active" checked>
                    <label class="checkbox-label-enterprise" for="is_active">Active</label>
                </div>
                <div class="form-help-text">Disable to temporarily deactivate this discount code</div>
            </div>
        </div>
        <div class="modal-footer-enterprise">
            <button type="button" class="btn-enterprise btn-secondary-enterprise" onclick="closeDiscountModal()">Cancel</button>
            <button type="submit" name="create_discount" id="create_discount_btn" class="btn-enterprise btn-success-enterprise">
                <i class="fas fa-plus"></i> Create Discount
            </button>
            <button type="submit" name="update_discount" id="update_discount_btn" class="btn-enterprise btn-primary-enterprise" style="display: none;">
                <i class="fas fa-save"></i> Update Discount
            </button>
        </div>
    </form>
</div>

<script>
    // Loading overlay functions
    function showLoading() {
        document.getElementById('loadingOverlay').classList.add('show');
    }

    function hideLoading() {
        document.getElementById('loadingOverlay').classList.remove('show');
    }

    // Course Pricing Modal Functions
    function editCoursePricing(courseId, title, price, currency, isFree) {
        document.getElementById('course_id').value = courseId;
        document.getElementById('course_title').value = title;
        document.getElementById('price').value = price;
        document.getElementById('currency').value = currency;
        document.getElementById('is_free').checked = isFree;

        togglePriceFields();

        openModal('coursePricingModal', 'coursePricingModalBackdrop');
    }

    function togglePriceFields() {
        const isFree = document.getElementById('is_free').checked;
        const priceFields = document.getElementById('price_fields');
        const priceInput = document.getElementById('price');

        if (isFree) {
            priceFields.classList.add('hidden');
            priceInput.removeAttribute('required');
        } else {
            priceFields.classList.remove('hidden');
            priceInput.setAttribute('required', 'required');
        }
    }

    function closeCoursePricingModal() {
        closeModal('coursePricingModal', 'coursePricingModalBackdrop');
    }

    // Discount Modal Functions
    function showCreateDiscountModal() {
        document.getElementById('discountModalTitle').innerHTML = '<i class="fas fa-tag"></i> Create Discount Code';
        document.getElementById('discount_id').value = '';
        document.getElementById('code').value = '';
        document.getElementById('description').value = '';
        document.getElementById('discount_type').value = 'percentage';
        document.getElementById('discount_value').value = '';
        document.getElementById('min_purchase').value = '0';
        document.getElementById('usage_limit').value = '';
        document.getElementById('valid_from').value = '';
        document.getElementById('valid_until').value = '';
        document.getElementById('is_active').checked = true;

        document.getElementById('create_discount_btn').style.display = 'inline-flex';
        document.getElementById('update_discount_btn').style.display = 'none';
        document.getElementById('active_field').style.display = 'none';

        updateValueHelp();

        openModal('discountModal', 'discountModalBackdrop');
    }

    function editDiscount(discount) {
        document.getElementById('discountModalTitle').innerHTML = '<i class="fas fa-edit"></i> Edit Discount Code';
        document.getElementById('discount_id').value = discount.id;
        document.getElementById('code').value = discount.code;
        document.getElementById('description').value = discount.description;
        document.getElementById('discount_type').value = discount.discount_type;
        document.getElementById('discount_value').value = discount.discount_value;
        document.getElementById('min_purchase').value = discount.min_purchase_amount;
        document.getElementById('usage_limit').value = discount.usage_limit || '';
        document.getElementById('valid_from').value = discount.valid_from ? discount.valid_from.split(' ')[0] : '';
        document.getElementById('valid_until').value = discount.valid_until ? discount.valid_until.split(' ')[0] : '';
        document.getElementById('is_active').checked = discount.is_active == 1;

        document.getElementById('create_discount_btn').style.display = 'none';
        document.getElementById('update_discount_btn').style.display = 'inline-flex';
        document.getElementById('active_field').style.display = 'block';

        updateValueHelp();

        openModal('discountModal', 'discountModalBackdrop');
    }

    function updateValueHelp() {
        const type = document.getElementById('discount_type').value;
        const help = document.getElementById('value_help');
        const valueInput = document.getElementById('discount_value');
        
        if (type === 'percentage') {
            help.textContent = 'Percentage (0-100)';
            valueInput.max = 100;
        } else {
            help.textContent = 'Fixed amount in selected currency';
            valueInput.removeAttribute('max');
        }
    }

    function closeDiscountModal() {
        closeModal('discountModal', 'discountModalBackdrop');
    }

    function deleteDiscount(id, code) {
        if (confirm(`Are you sure you want to delete the discount code "${code}"? This action cannot be undone.`)) {
            showLoading();
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="discount_id" value="${id}">
                <input type="hidden" name="delete_discount" value="1">
            `;
            document.body.appendChild(form);
            form.submit();
        }
    }

    // Modal helper functions
    function openModal(modalId, backdropId) {
        document.getElementById(modalId).classList.add('show');
        document.getElementById(backdropId).classList.add('show');
        document.body.style.overflow = 'hidden';
        
        // Focus first input
        setTimeout(() => {
            const firstInput = document.getElementById(modalId).querySelector('input:not([readonly])');
            if (firstInput) {
                firstInput.focus();
            }
        }, 100);
    }

    function closeModal(modalId, backdropId) {
        document.getElementById(modalId).classList.remove('show');
        document.getElementById(backdropId).classList.remove('show');
        document.body.style.overflow = '';
    }

    // Keyboard accessibility
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            closeCoursePricingModal();
            closeDiscountModal();
        }
    });

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        togglePriceFields();
        
        // Add smooth scroll behavior for any anchor links
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({ behavior: 'smooth' });
                }
            });
        });
    });

    // Form validation
    document.getElementById('discountForm').addEventListener('submit', function(e) {
        const code = document.getElementById('code').value;
        const description = document.getElementById('description').value;
        const discountValue = parseFloat(document.getElementById('discount_value').value);
        const discountType = document.getElementById('discount_type').value;
        
        // Validate discount value
        if (discountType === 'percentage' && discountValue > 100) {
            e.preventDefault();
            alert('Percentage discount cannot exceed 100%.');
            return false;
        }
        
        if (discountValue < 0) {
            e.preventDefault();
            alert('Discount value must be positive.');
            return false;
        }
        
        showLoading();
    });

    document.getElementById('coursePricingForm').addEventListener('submit', function() {
        showLoading();
    });
</script>

<?php include 'includes/admin_footer.php'; ?>
