<?php
/** @var array $courses */
/** @var array $lockedPatterns */
/** @var string $csrfToken */

$bp = defined('BASE_PATH') ? BASE_PATH : '/gmind';
$flash_error = $_SESSION['flash']['error'] ?? '';
$flash_success = $_SESSION['flash']['success'] ?? '';
unset($_SESSION['flash']);

$hasLockedPatterns = !empty($lockedPatterns);
?>
<style>
.course-row { transition: background 0.2s; }
.course-row:hover { background: #f8f9fa; }
.status-badge {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 0.75rem;
    font-weight: 600;
}
.status-assigned { background: #d4edda; color: #155724; }
.status-pending { background: #fff3cd; color: #856404; }
</style>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1"><i class="fas fa-link"></i> Assign Patterns to Courses</h2>
            <p class="text-muted mb-0">Assign locked patterns to courses — branch admins will auto-use these for certificate & marksheet generation</p>
        </div>
        <a href="<?= $bp ?>/super-admin/patterns" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Back to Patterns
        </a>
    </div>

    <?php if ($flash_error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($flash_error) ?></div>
    <?php endif; ?>
    <?php if ($flash_success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($flash_success) ?></div>
    <?php endif; ?>

    <?php if (!$hasLockedPatterns): ?>
        <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <strong>No locked patterns!</strong> You need to lock at least one pattern before assigning to courses.
            <a href="<?= $bp ?>/super-admin/patterns" class="alert-link">Go to Patterns</a> to create and lock one.
        </div>
    <?php endif; ?>

    <?php if (empty($courses)): ?>
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-book fa-4x text-muted mb-3"></i>
                <h5 class="text-muted">No courses found</h5>
                <p class="text-muted">Create courses first in the admin panel</p>
            </div>
        </div>
    <?php else: ?>
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-list"></i> Courses (<?= count($courses) ?>)</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th width="40">#</th>
                                <th>Course Name</th>
                                <th width="180">Certificate Pattern</th>
                                <th width="180">Marksheet Pattern</th>
                                <th width="200">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($courses as $i => $c): ?>
                                <?php
                                $certAssigned = !empty($c['cert_pattern_id']);
                                $marksheetAssigned = !empty($c['marksheet_pattern_id']);
                                $bothAssigned = $certAssigned && $marksheetAssigned;
                                ?>
                                <tr class="course-row" data-course-id="<?= (int)$c['id'] ?>">
                                    <td><?= $i + 1 ?></td>
                                    <td>
                                        <strong><?= htmlspecialchars($c['name'] ?? 'Unknown') ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($c['duration'] ?? '') ?> • <?= htmlspecialchars($c['course_code'] ?? '') ?></small>
                                    </td>
                                    <td>
                                        <select class="form-select form-select-sm cert-pattern-select" data-course-id="<?= (int)$c['id'] ?>" <?= !$hasLockedPatterns ? 'disabled' : '' ?>>
                                            <option value="0">— None —</option>
                                            <?php foreach ($lockedPatterns as $p): ?>
                                                <option value="<?= (int)$p['id'] ?>" <?= ($c['cert_pattern_id'] == $p['id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($p['name']) ?>
                                                    <?= !empty($p['is_default']) ? ' ⭐' : '' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if ($certAssigned): ?>
                                            <span class="status-badge status-assigned">Assigned</span>
                                        <?php else: ?>
                                            <span class="status-badge status-pending">Not set</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <select class="form-select form-select-sm marksheet-pattern-select" data-course-id="<?= (int)$c['id'] ?>" <?= !$hasLockedPatterns ? 'disabled' : '' ?>>
                                            <option value="0">— None —</option>
                                            <?php foreach ($lockedPatterns as $p): ?>
                                                <option value="<?= (int)$p['id'] ?>" <?= ($c['marksheet_pattern_id'] == $p['id']) ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($p['name']) ?>
                                                    <?= !empty($p['is_default']) ? ' ⭐' : '' ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <?php if ($marksheetAssigned): ?>
                                            <span class="status-badge status-assigned">Assigned</span>
                                        <?php else: ?>
                                            <span class="status-badge status-pending">Not set</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if ($bothAssigned): ?>
                                            <div class="btn-group btn-group-sm">
                                                <a href="<?= $bp ?>/super-admin/patterns/test-generate?course_id=<?= (int)$c['id'] ?>&doc_type=certificate"
                                                   target="_blank" class="btn btn-outline-info" title="Test Certificate PDF">
                                                    <i class="fas fa-certificate"></i> Cert
                                                </a>
                                                <a href="<?= $bp ?>/super-admin/patterns/test-generate?course_id=<?= (int)$c['id'] ?>&doc_type=marksheet"
                                                   target="_blank" class="btn btn-outline-info" title="Test Marksheet PDF">
                                                    <i class="fas fa-file-alt"></i> Marksheet
                                                </a>
                                            </div>
                                        <?php else: ?>
                                            <button class="btn btn-sm btn-outline-secondary" disabled title="Assign both patterns first">
                                                <i class="fas fa-lock"></i> Locked
                                            </button>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-body">
                <h6><i class="fas fa-info-circle text-info"></i> How it works:</h6>
                <ol class="mb-0">
                    <li>Select a <strong>Certificate Pattern</strong> from dropdown for each course</li>
                    <li>Select a <strong>Marksheet Pattern</strong> from dropdown for each course</li>
                    <li>Selections auto-save when changed (you'll see a toast notification)</li>
                    <li>Once both patterns are assigned, "Cert" and "Marksheet" test buttons appear</li>
                    <li>Click test buttons to generate PDF with sample student data</li>
                    <li>If PDF looks correct, branch admins can now generate real certificates for this course</li>
                </ol>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
const BASE_PATH = '<?= $bp ?>';
const CSRF_TOKEN = '<?= htmlspecialchars($csrfToken, ENT_QUOTES) ?>';

function savePattern(courseId, docType, patternId) {
    // ✅ FIX: Read BOTH dropdowns' current values so we don't lose one when saving the other
    const certSel = document.querySelector('.cert-pattern-select[data-course-id="' + courseId + '"]');
    const marksheetSel = document.querySelector('.marksheet-pattern-select[data-course-id="' + courseId + '"]');

    const certPatternId = certSel ? certSel.value : 0;
    const marksheetPatternId = marksheetSel ? marksheetSel.value : 0;

    const formData = new FormData();
    formData.append('course_id', courseId);
    formData.append('cert_pattern_id', certPatternId);
    formData.append('marksheet_pattern_id', marksheetPatternId);
    formData.append('csrf_token', CSRF_TOKEN);

    showToast('Saving ' + docType + ' pattern...', 'info');
    fetch(BASE_PATH + '/super-admin/patterns/course-assignment/save', {
        method: 'POST',
        body: formData,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-Token': CSRF_TOKEN
        }
    }).then(r => r.json()).then(data => {
        if (data.success) {
            showToast(data.message || 'Saved!', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Error: ' + (data.error || 'Unknown'), 'error');
        }
    }).catch(e => showToast('Error: ' + e.message, 'error'));
}

// Listen for changes on cert pattern selects
document.querySelectorAll('.cert-pattern-select').forEach(sel => {
    sel.addEventListener('change', (e) => {
        const courseId = e.target.getAttribute('data-course-id');
        const patternId = e.target.value;
        savePattern(courseId, 'certificate', patternId);
    });
});

// Listen for changes on marksheet pattern selects
document.querySelectorAll('.marksheet-pattern-select').forEach(sel => {
    sel.addEventListener('change', (e) => {
        const courseId = e.target.getAttribute('data-course-id');
        const patternId = e.target.value;
        savePattern(courseId, 'marksheet', patternId);
    });
});

function showToast(msg, type='info') {
    const colors = { success: 'bg-success', error: 'bg-danger', info: 'bg-info' };
    const toast = document.createElement('div');
    toast.className = `toast show align-items-center text-white ${colors[type] || 'bg-info'} border-0 position-fixed`;
    toast.style.cssText = 'top:20px;right:20px;z-index:9999;min-width:300px;';
    toast.innerHTML = `<div class="d-flex"><div class="toast-body">${msg}</div><button type="button" class="btn-close btn-close-white me-2 m-auto" onclick="this.parentElement.parentElement.remove()"></button></div>`;
    document.body.appendChild(toast);
    setTimeout(() => toast.remove(), 4000);
}
</script>
