<?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_exam_pricing'])) {
        // Update exam pricing
        $examId = (int)$_POST['exam_id'];
        $price = (float)$_POST['price'];
        $currency = trim($_POST['currency']);
        $isFree = isset($_POST['is_free']) ? 1 : 0;

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

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

            $success = 'Exam 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;

        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;

        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 exams for pricing management
$query = "SELECT e.*, u.username as instructor_name
          FROM exams e
          LEFT JOIN users u ON e.instructor_id = u.id";

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

$exams = $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 = 'Exam Pricing Management';
include 'includes/admin_header.php';
?>

<div class="exam-pricing-page">
    <div class="admin-content">
        <div class="exam-pricing-header">
            <h1>Exam Pricing Management</h1>
            <p>Manage exam prices, currencies, and discount codes for your exams</p>
        </div>

        <!-- Pricing Stats - Horizontal Layout -->
        <div class="pricing-stats-horizontal">
            <div class="pricing-stat-card">
                <div class="stat-icon">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count($exams); ?></div>
                    <div class="stat-label">Total Exams</div>
                </div>
            </div>
            <div class="pricing-stat-card">
                <div class="stat-icon free">
                    <i class="fas fa-gift"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count(array_filter($exams, function($e) { return $e['is_free']; })); ?></div>
                    <div class="stat-label">Free Exams</div>
                </div>
            </div>
            <div class="pricing-stat-card">
                <div class="stat-icon paid">
                    <i class="fas fa-dollar-sign"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count(array_filter($exams, function($e) { return !$e['is_free']; })); ?></div>
                    <div class="stat-label">Paid Exams</div>
                </div>
            </div>
            <div class="pricing-stat-card">
                <div class="stat-icon discount">
                    <i class="fas fa-tags"></i>
                </div>
                <div class="stat-content">
                    <div class="stat-number"><?php echo count($discounts); ?></div>
                    <div class="stat-label">Active Discounts</div>
                </div>
            </div>
        </div>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Tables Container - Aligned Layout -->
        <div class="pricing-tables-container">
            <!-- Exam Pricing Table -->
            <div class="pricing-table-section">
                <div class="table-header">
                    <h3>Exam Pricing</h3>
                    <p>Manage pricing for your exams</p>
                </div>
                <div class="table-wrapper">
                    <table class="aligned-table pricing-table">
                        <thead>
                            <tr>
                                <th>Exam</th>
                                <th>Instructor</th>
                                <th>Price</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($exams)): ?>
                                <tr>
                                    <td colspan="5">
                                        <div class="empty-state">
                                            <div class="empty-state-icon">
                                                <i class="fas fa-file-alt"></i>
                                            </div>
                                            <h4>No Exams Found</h4>
                                            <p>No exams available for pricing management.</p>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($exams as $exam): ?>
                                    <tr>
                                        <td>
                                            <div class="exam-info">
                                                <strong><?php echo htmlspecialchars($exam['title']); ?></strong>
                                                <div class="exam-meta">ID: <?php echo $exam['id']; ?></div>
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($exam['instructor_name']); ?></td>
                                        <td>
                                            <?php if ($exam['is_free']): ?>
                                                <span class="price-badge free">
                                                    <i class="fas fa-gift"></i> Free
                                                </span>
                                            <?php else: ?>
                                                <span class="price-badge paid">
                                                    <i class="fas fa-dollar-sign"></i>
                                                    <?php echo htmlspecialchars($exam['currency']); ?> <?php echo number_format($exam['price'], 2); ?>
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-badge <?php echo $exam['status'] === 'published' ? 'published' : 'draft'; ?>">
                                                <i class="fas fa-<?php echo $exam['status'] === 'published' ? 'check-circle' : 'clock'; ?>"></i>
                                                <?php echo ucfirst($exam['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button class="table-action-btn edit" onclick="editExamPricing(<?php echo $exam['id']; ?>, '<?php echo addslashes($exam['title']); ?>', <?php echo $exam['price']; ?>, '<?php echo $exam['currency']; ?>', <?php echo $exam['is_free'] ? 'true' : 'false'; ?>)">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Discount Codes Table -->
            <div class="discount-table-section">
                <div class="table-header">
                    <div>
                        <h3>Discount Codes</h3>
                        <p>Manage promotional codes and discounts</p>
                    </div>
                    <button class="btn btn-primary add-discount-btn" onclick="showCreateDiscountModal()">
                        <i class="fas fa-plus"></i> Create Code
                    </button>
                </div>
                <div class="table-wrapper">
                    <table class="aligned-table discount-table">
                        <thead>
                            <tr>
                                <th>Code</th>
                                <th>Description</th>
                                <th>Type</th>
                                <th>Value</th>
                                <th>Usage</th>
                                <th>Valid Until</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($discounts)): ?>
                                <tr>
                                    <td colspan="8">
                                        <div class="empty-state">
                                            <div class="empty-state-icon">
                                                <i class="fas fa-tags"></i>
                                            </div>
                                            <h4>No Discount Codes</h4>
                                            <p>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"><?php echo htmlspecialchars($discount['code']); ?></code>
                                        </td>
                                        <td><?php echo htmlspecialchars($discount['description']); ?></td>
                                        <td>
                                            <span class="discount-type <?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>
                                            <span class="discount-value">
                                                <?php if ($discount['discount_type'] === 'percentage'): ?>
                                                    <?php echo $discount['discount_value']; ?>%
                                                <?php else: ?>
                                                    $<?php echo number_format($discount['discount_value'], 2); ?>
                                                <?php endif; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="usage-info">
                                                <span class="usage-count"><?php echo $discount['usage_count']; ?></span>
                                                <?php if ($discount['usage_limit']): ?>
                                                    <span class="usage-limit">/ <?php echo $discount['usage_limit']; ?></span>
                                                <?php else: ?>
                                                    <span class="usage-unlimited">unlimited</span>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <?php if ($discount['valid_until']): ?>
                                                <span class="validity-date"><?php echo date('M j, Y', strtotime($discount['valid_until'])); ?></span>
                                            <?php else: ?>
                                                <span class="validity-unlimited">No expiry</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="discount-status <?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="table-actions">
                                                <button class="table-action-btn edit" onclick="editDiscount(<?php echo htmlspecialchars(json_encode($discount)); ?>)">
                                                    <i class="fas fa-edit"></i> Edit
                                                </button>
                                                <button class="table-action-btn delete" onclick="deleteDiscount(<?php echo $discount['id']; ?>, '<?php echo addslashes($discount['code']); ?>')">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Exam Pricing Modal -->
<div class="modal fade" id="examPricingModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Exam Pricing</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="exam_id" id="exam_id">
                    <div class="mb-3">
                        <label class="form-label">Exam</label>
                        <input type="text" class="form-control" id="exam_title" readonly>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="is_free" name="is_free">
                            <label class="form-check-label" for="is_free">
                                This exam is free
                            </label>
                        </div>
                    </div>
                    <div class="mb-3" id="price_fields">
                        <label for="price" class="form-label">Price</label>
                        <div class="input-group">
                            <select class="form-select" name="currency" id="currency" style="max-width: 100px;">
                                <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-control" name="price" id="price" step="0.01" min="0">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="update_exam_pricing" class="btn btn-primary">Update Pricing</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Discount Modal -->
<div class="modal fade" id="discountModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="discountModalTitle">Create Discount Code</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="discount_id" id="discount_id">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="code" class="form-label">Discount Code *</label>
                            <input type="text" class="form-control" name="code" id="code" required style="text-transform: uppercase;">
                            <div class="form-text">Unique code for the discount (e.g., SAVE10)</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="discount_type" class="form-label">Discount Type *</label>
                            <select class="form-select" name="discount_type" id="discount_type" required>
                                <option value="percentage">Percentage</option>
                                <option value="fixed_amount">Fixed Amount</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">Description *</label>
                        <input type="text" class="form-control" name="description" id="description" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="discount_value" class="form-label">Discount Value *</label>
                            <input type="number" class="form-control" name="discount_value" id="discount_value" step="0.01" min="0" required>
                            <div class="form-text" id="value_help">Percentage (0-100) or fixed amount</div>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label for="min_purchase" class="form-label">Minimum Purchase</label>
                            <input type="number" class="form-control" name="min_purchase" id="min_purchase" step="0.01" min="0" value="0">
                            <div class="form-text">Minimum order amount to use this discount</div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="usage_limit" class="form-label">Usage Limit</label>
                            <input type="number" class="form-control" name="usage_limit" id="usage_limit" min="1">
                            <div class="form-text">Leave empty for unlimited usage</div>
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="valid_from" class="form-label">Valid From</label>
                            <input type="date" class="form-control" name="valid_from" id="valid_from">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label for="valid_until" class="form-label">Valid Until</label>
                            <input type="date" class="form-control" name="valid_until" id="valid_until">
                        </div>
                    </div>
                    <div class="mb-3" id="active_field">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="is_active" name="is_active" checked>
                            <label class="form-check-label" for="is_active">
                                Active
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="create_discount" id="create_discount_btn" class="btn btn-primary">Create Discount</button>
                    <button type="submit" name="update_discount" id="update_discount_btn" class="btn btn-primary" style="display: none;">Update Discount</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
function editExamPricing(examId, title, price, currency, isFree) {
    document.getElementById('exam_id').value = examId;
    document.getElementById('exam_title').value = title;
    document.getElementById('price').value = price;
    document.getElementById('currency').value = currency;
    document.getElementById('is_free').checked = isFree;

    togglePriceFields(!isFree);

    const modal = new bootstrap.Modal(document.getElementById('examPricingModal'));
    modal.show();
}

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

    if (show) {
        priceFields.style.display = 'block';
        priceInput.required = true;
    } else {
        priceFields.style.display = 'none';
        priceInput.required = false;
    }
}

document.getElementById('is_free').addEventListener('change', function() {
    togglePriceFields(!this.checked);
});

function showCreateDiscountModal() {
    document.getElementById('discountModalTitle').textContent = '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-block';
    document.getElementById('update_discount_btn').style.display = 'none';
    document.getElementById('active_field').style.display = 'none';

    updateValueHelp('percentage');

    const modal = new bootstrap.Modal(document.getElementById('discountModal'));
    modal.show();
}

function editDiscount(discount) {
    document.getElementById('discountModalTitle').textContent = '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-block';
    document.getElementById('active_field').style.display = 'block';

    updateValueHelp(discount.discount_type);

    const modal = new bootstrap.Modal(document.getElementById('discountModal'));
    modal.show();
}

function updateValueHelp(type) {
    const help = document.getElementById('value_help');
    if (type === 'percentage') {
        help.textContent = 'Percentage (0-100)';
    } else {
        help.textContent = 'Fixed amount in USD';
    }
}

document.getElementById('discount_type').addEventListener('change', function() {
    updateValueHelp(this.value);
});

function deleteDiscount(id, code) {
    if (confirm(`Are you sure you want to delete the discount code "${code}"?`)) {
        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();
    }
}

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    togglePriceFields(!document.getElementById('is_free').checked);
});
</script>

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