@extends('admin.layouts.app')

@section('title', 'Edit Exam Template')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('exam-templates.index') }}">Templates</a></li>
    <li class="breadcrumb-item active" aria-current="page">Edit</li>
@endsection

@section('content')

    <div class="row">
        <div class="col-12">
            <form action="{{ route('exam-templates.update', $examTemplate->id) }}" method="POST" id="templateForm">
                @csrf
                @method('PUT')

                <!-- Template Info Card -->
                <div class="card mb-4 shadow-sm">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold"><i class="bi bi-pencil-square me-2 text-primary"></i>Edit Template
                            Information</h6>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label for="name" class="form-label small fw-bold text-muted">Template Name <span
                                        class="text-danger">*</span></label>
                                <input type="text" name="name" id="name" value="{{ old('name', $examTemplate->name) }}"
                                    class="form-control" required>
                                @error('name') <div class="text-danger small mt-1">{{ $message }}</div> @enderror
                            </div>
                            <div class="col-md-6">
                                <label for="description" class="form-label small fw-bold text-muted">Description</label>
                                <input type="text" name="description" id="description"
                                    value="{{ old('description', $examTemplate->description) }}" class="form-control">
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Subject Rules Container -->
                <div id="subjectRulesContainer">
                    <!-- Rules will be loaded via JS -->
                </div>

                <!-- Add Subject Button -->
                <div class="d-grid gap-2 mb-4">
                    <button type="button" class="btn btn-outline-primary border-dashed py-3" id="addSubjectRule">
                        <i class="bi bi-plus-circle me-2"></i> Add Another Subject Rule
                    </button>
                </div>

                @error('subject_rules') <div class="alert alert-danger">{{ $message }}</div> @enderror

                <!-- Action Buttons -->
                <div class="card bg-transparent border-0 mb-5">
                    <div class="d-flex justify-content-end gap-2">
                        <a href="{{ route('exam-templates.index') }}" class="btn btn-light border px-4">Cancel</a>
                        <button type="submit" class="btn btn-primary px-4 shadow-sm"><i class="bi bi-check-lg me-1"></i>
                            Update Template</button>
                    </div>
                </div>

            </form>
        </div>
    </div>

    <script>
        let subjectRuleIndex = 0;
        const subjects = @json($subjects);
        const existingRules = @json($examTemplate->subjectRules);

        document.addEventListener('DOMContentLoaded', () => {
            if (existingRules && existingRules.length > 0) {
                existingRules.forEach(rule => {
                    addSubjectRule(rule);
                });
            } else {
                addSubjectRule();
            }
        });

        document.getElementById('addSubjectRule').addEventListener('click', function () {
            addSubjectRule();
        });

        function addSubjectRule(existingRule = null) {
            const container = document.getElementById('subjectRulesContainer');
            const ruleDiv = document.createElement('div');
            ruleDiv.className = 'card mb-4 border-primary shadow-sm';
            ruleDiv.dataset.index = subjectRuleIndex;

            const selectedSubjectId = existingRule?.subject_id || '';
            const totalMarks = existingRule?.total_marks || '';
            const passMarks = existingRule?.pass_marks || '';
            const paperMode = existingRule?.paper_mode || 'merged';
            const config = existingRule?.config ? (typeof existingRule.config === 'string' ? JSON.parse(existingRule.config) : existingRule.config) : {};

            // Get all currently selected subject IDs to filter them out
            const selectedSubjects = getSelectedSubjectIds();

            // Generate Options - Filter out already selected subjects
            let subjectOptions = `<option value="">-- Choose Subject --</option>`;
            subjects.forEach(s => {
                // Skip if this subject is already selected in another rule (unless it's the current rule being edited)
                if (selectedSubjects.includes(s.id.toString()) && s.id.toString() !== selectedSubjectId.toString()) {
                    return; // Skip this subject
                }
                const isSelected = selectedSubjectId == s.id ? 'selected' : '';
                const hasMcq = (s.has_mcq !== undefined && s.has_mcq !== null) ? s.has_mcq : 1;
                const hasCq = (s.has_cq !== undefined && s.has_cq !== null) ? s.has_cq : 1;
                subjectOptions += `<option value="${s.id}" data-type="${s.type}" data-has-practical="${s.has_practical}" data-has-mcq="${hasMcq}" data-has-cq="${hasCq}" ${isSelected}>${s.name} (${s.code})</option>`;
            });

            ruleDiv.innerHTML = `
                <div class="card-header bg-primary bg-opacity-10 d-flex justify-content-between align-items-center">
                    <h6 class="mb-0 fw-bold text-primary"><span class="badge bg-primary me-2">${subjectRuleIndex + 1}</span> <span id="subject_name_${subjectRuleIndex}">Subject Configuration</span></h6>
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm btn-outline-info border-0" onclick="duplicateSubjectRule(this)" title="Duplicate Rule"><i class="bi bi-copy"></i></button>
                        <button type="button" class="btn btn-sm btn-outline-danger border-0" onclick="removeSubjectRule(this)" title="Remove"><i class="bi bi-trash"></i></button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Subject <span class="text-danger">*</span></label>
                            <select name="subject_rules[${subjectRuleIndex}][subject_id]" id="subject_select_${subjectRuleIndex}" class="form-select" onchange="onSubjectChange(${subjectRuleIndex})" required>
                                ${subjectOptions}
                            </select>
                        </div>
                        <div class="col-md-6" id="paper_mode_container_${subjectRuleIndex}" style="display:none;">
                             <label class="form-label small fw-bold text-muted">Paper Mode</label>
                             <select id="paper_mode_select_${subjectRuleIndex}" class="form-select" onchange="onPaperModeChange(${subjectRuleIndex})">
                                <option value="merged" ${paperMode === 'merged' ? 'selected' : ''}>Merged (Single Entry)</option>
                                <option value="separate" ${paperMode === 'separate' ? 'selected' : ''}>Separate (1st & 2nd Paper)</option>
                            </select>
                        </div>
                    </div>

                    <!-- Dynamic Config Fields -->
                    <div id="config_container_${subjectRuleIndex}" class="bg-light p-3 rounded mb-3 border">
                        <p class="text-muted small text-center mb-0">Select a subject to configure marks.</p>
                    </div>

                     <!-- Totals -->
                    <div class="row g-3 border-top pt-3">
                         <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Total Marks <span class="text-danger">*</span></label>
                            <input type="number" name="subject_rules[${subjectRuleIndex}][total_marks]" id="total_marks_${subjectRuleIndex}" value="${totalMarks}" class="form-control" required readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label small fw-bold text-muted">Pass Marks <span class="text-danger">*</span></label>
                            <input type="number" name="subject_rules[${subjectRuleIndex}][pass_marks]" id="pass_marks_${subjectRuleIndex}" value="${passMarks}" class="form-control" required>
                            <div class="form-text small">Overall pass mark required.</div>
                        </div>
                    </div>

                    <input type="hidden" name="subject_rules[${subjectRuleIndex}][paper_mode]" id="paper_mode_${subjectRuleIndex}" value="${paperMode}">
                    <input type="hidden" name="subject_rules[${subjectRuleIndex}][config]" id="config_json_${subjectRuleIndex}" value='${JSON.stringify(config)}'>
                </div>
            `;

            container.appendChild(ruleDiv);

            // If explicitly setting a subject (like in duplicate), trigger change and verify
            if (selectedSubjectId) {
                // 1. Trigger subject change to generate form fields
                onSubjectChange(subjectRuleIndex, existingRule?.config || null);

                // 2. If we have duplicated data, populate it now
                if (existingRule) {
                    // Restore Paper Mode
                    if (existingRule.paper_mode) {
                        const paperModeSelect = document.getElementById(`paper_mode_select_${subjectRuleIndex}`);
                        if (paperModeSelect) {
                            paperModeSelect.value = existingRule.paper_mode;
                            // Trigger paper mode change to update fields
                            onPaperModeChange(subjectRuleIndex, existingRule?.config || null);
                        }
                    }

                    // Restore Config
                    if (existingRule.config) {
                        const config = existingRule.config; // Already parsed in edit view logic usually

                        const setValue = (id, val) => {
                            const el = document.getElementById(id);
                            if (el) el.value = val !== undefined ? val : '';
                        };

                        const setChecked = (id, val) => {
                            const el = document.getElementById(id);
                            if (el) el.checked = !!val;
                        };

                        // Handle Merged Mode (Flat keys for marks, Nested for pass)
                        if (!existingRule.paper_mode || existingRule.paper_mode === 'merged') {
                            setValue(`mcq_${subjectRuleIndex}`, config.mcq);
                            setValue(`cq_${subjectRuleIndex}`, config.cq);
                            setValue(`practical_${subjectRuleIndex}`, config.practical);

                            if (config.pass_config) {
                                setValue(`mcq_pass_${subjectRuleIndex}`, config.pass_config.mcq);
                                setValue(`cq_pass_${subjectRuleIndex}`, config.pass_config.cq);
                                setValue(`practical_pass_${subjectRuleIndex}`, config.pass_config.practical);

                                setChecked(`mcq_must_pass_${subjectRuleIndex}`, config.pass_config.mcq_must_pass);
                                setChecked(`cq_must_pass_${subjectRuleIndex}`, config.pass_config.cq_must_pass);
                                setChecked(`practical_must_pass_${subjectRuleIndex}`, config.pass_config.practical_must_pass);
                            }
                        }

                        // Handle Separate Mode (Nested mark_distribution)
                        if (existingRule.paper_mode === 'separate' && config.mark_distribution) {
                            const dist = config.mark_distribution;

                            if (dist.first_paper) {
                                setValue(`first_mcq_${subjectRuleIndex}`, dist.first_paper.mcq);
                                setValue(`first_cq_${subjectRuleIndex}`, dist.first_paper.cq);
                                // setValue(`first_practical_${subjectRuleIndex}`, dist.first_paper.practical); 
                            }

                            if (dist.second_paper) {
                                setValue(`second_mcq_${subjectRuleIndex}`, dist.second_paper.mcq);
                                setValue(`second_cq_${subjectRuleIndex}`, dist.second_paper.cq);
                                setValue(`second_practical_${subjectRuleIndex}`, dist.second_paper.practical);
                            }

                            // Combined Pass Marks (in pass_config)
                            if (config.pass_config) {
                                setValue(`combined_cq_pass_${subjectRuleIndex}`, config.pass_config.cq);
                                setValue(`combined_mcq_pass_${subjectRuleIndex}`, config.pass_config.mcq);
                                setValue(`combined_practical_pass_${subjectRuleIndex}`, config.pass_config.practical);
                            }
                        }
                    }

                    if (existingRule.total_marks) {
                        document.getElementById(`total_marks_${subjectRuleIndex}`).value = existingRule.total_marks;
                    }

                    // Restore Pass Marks
                    if (existingRule.pass_marks) {
                        document.getElementById(`pass_marks_${subjectRuleIndex}`).value = existingRule.pass_marks;
                    }
                }
            }

            subjectRuleIndex++;
        }

        function removeSubjectRule(btn) {
            if (confirm('Remove this subject rule?')) {
                btn.closest('.card').remove();
            }
        }

        function duplicateSubjectRule(btn) {
            const card = btn.closest('.card');
            const index = parseInt(card.dataset.index);

            // Get current values
            const totalMarks = document.getElementById(`total_marks_${index}`).value;
            const passMarks = document.getElementById(`pass_marks_${index}`).value;
            const configJson = document.getElementById(`config_json_${index}`).value;
            const paperMode = document.getElementById(`paper_mode_${index}`).value;

            // Find next available subject (not already selected)
            const selectedSubjects = getSelectedSubjectIds();
            let nextSubjectId = '';

            for (let subject of subjects) {
                if (!selectedSubjects.includes(subject.id.toString())) {
                    nextSubjectId = subject.id;
                    break;
                }
            }

            if (!nextSubjectId) {
                alert('No more subjects available to duplicate!');
                return;
            }

            // Create a rule object with next available subject
            const ruleData = {
                subject_id: nextSubjectId,
                total_marks: totalMarks,
                pass_marks: passMarks,
                paper_mode: paperMode,
                config: JSON.parse(configJson)
            };

            // Add new rule with duplicated configuration
            addSubjectRule(ruleData);
        }

        function getSelectedSubjectIds() {
            const selectedIds = [];
            document.querySelectorAll('[id^="subject_select_"]').forEach(select => {
                if (select.value) {
                    selectedIds.push(select.value);
                }
            });
            return selectedIds;
        }

        function onSubjectChange(index, prefillConfig = null) {
            const select = document.getElementById(`subject_select_${index}`);
            const option = select.options[select.selectedIndex];

            if (!option.value) {
                document.getElementById(`config_container_${index}`).innerHTML = '<p class="text-muted small text-center mb-0">Select a subject first.</p>';
                document.getElementById(`paper_mode_container_${index}`).style.display = 'none';
                return;
            }

            document.getElementById(`subject_name_${index}`).innerText = option.text;

            // Show paper mode selector
            const paperModeContainer = document.getElementById(`paper_mode_container_${index}`);
            paperModeContainer.style.display = 'block';

            // Trigger change to render fields
            onPaperModeChange(index, prefillConfig);
        }

        function onPaperModeChange(index, prefillConfig = null) {
            const mode = document.getElementById(`paper_mode_select_${index}`).value;
            document.getElementById(`paper_mode_${index}`).value = mode;

            const configContainer = document.getElementById(`config_container_${index}`);

            const subjectSelect = document.getElementById(`subject_select_${index}`);
            const subjectOption = subjectSelect.options[subjectSelect.selectedIndex];
            const hasPractical = subjectOption.getAttribute('data-has-practical') == '1';
            const hasCq = subjectOption.getAttribute('data-has-cq') == '1';
            const hasMcq = subjectOption.getAttribute('data-has-mcq') == '1';

            // Parse prefillConfig if it's string (shouldn't be, passed as obj)
            // But when triggered from select change manually, prefillConfig is null.
            // When triggered from initial load, it has value.
            // Wait, if I change Paper Mode, prefillConfig should be cleared? 
            // For now, let's just render fields. Values filling is tricky if structure changes.
            // We will try to fill if keys match.

            let html = '';
            if (mode === 'merged') {
                html = getMergedFields(index, hasCq, hasMcq, hasPractical, prefillConfig);
            } else {
                html = getSeparateFields(index, hasCq, hasMcq, hasPractical, prefillConfig);
            }
            configContainer.innerHTML = html;

            // If we don't have prefillConfig (user changed mode), assume 0 totals?
            if (!prefillConfig) {
                updateConfigJSON(index);
                calculateTotal(index);
            }
        }

        function getMergedFields(index, hasCq, hasMcq, hasPractical, config) {
            let html = '<div class="row g-3">';
            if (hasCq) html += generateFieldBlock(index, 'CQ', 'cq', 'bg-info bg-opacity-10 border-info', config?.cq, config?.pass_config?.cq, config?.pass_config?.cq_must_pass);
            if (hasMcq) html += generateFieldBlock(index, 'MCQ', 'mcq', 'bg-success bg-opacity-10 border-success', config?.mcq, config?.pass_config?.mcq, config?.pass_config?.mcq_must_pass);
            if (hasPractical) html += generateFieldBlock(index, 'Practical', 'practical', 'bg-warning bg-opacity-10 border-warning', config?.practical, config?.pass_config?.practical, config?.pass_config?.practical_must_pass);
            html += '</div>';
            return html;
        }

        function getSeparateFields(index, hasCq, hasMcq, hasPractical, config) {
            let html = '<div class="alert alert-info py-2 small"><i class="bi bi-info-circle me-1"></i> Configuring separately for 1st and 2nd Paper</div>';
            html += '<div class="row g-3">';

            // Config mapping for separate
            const marks = config?.mark_distribution || {};
            const p1 = marks.first_paper || {};
            const p2 = marks.second_paper || {};
            const pass = config?.pass_config || {};

            // 1st Paper
            html += '<div class="col-md-6"><div class="card card-body bg-light border p-2"><h6 class="small fw-bold">1st Paper</h6>';
            if (hasCq) html += generateSubField(index, 'first_cq', 'CQ', p1.cq);
            if (hasMcq) html += generateSubField(index, 'first_mcq', 'MCQ', p1.mcq);
            html += '</div></div>';

            // 2nd Paper
            html += '<div class="col-md-6"><div class="card card-body bg-light border p-2"><h6 class="small fw-bold">2nd Paper</h6>';
            if (hasCq) html += generateSubField(index, 'second_cq', 'CQ', p2.cq);
            if (hasMcq) html += generateSubField(index, 'second_mcq', 'MCQ', p2.mcq);
            if (hasPractical) html += generateSubField(index, 'second_practical', 'Practical', p2.practical);
            html += '</div></div>';

            html += '</div>';

            // Pass Config
            html += '<div class="mt-3"><h6 class="small fw-bold text-muted">Combined Pass Marks</h6><div class="row g-2">';
            if (hasCq) html += generatePassField(index, 'combined_cq_pass', 'CQ Pass', pass.cq);
            if (hasMcq) html += generatePassField(index, 'combined_mcq_pass', 'MCQ Pass', pass.mcq);
            if (hasPractical) html += generatePassField(index, 'combined_practical_pass', 'Prac. Pass', pass.practical);
            html += '</div></div>';

            return html;
        }

        function generateFieldBlock(index, label, key, classes, valTotal = '', valPass = '', checked = false) {
            return `
                <div class="col-md-4">
                    <div class="p-3 border rounded ${classes}">
                        <strong class="d-block small mb-2">${label}</strong>
                        <div class="mb-2">
                            <label class="small text-muted">Total</label>
                            <input type="number" id="${key}_${index}" value="${valTotal || ''}" class="form-control form-control-sm" placeholder="0" oninput="calculateTotal(${index}); updateConfigJSON(${index})">
                        </div>
                        <div class="mb-2">
                             <label class="small text-muted">Pass</label>
                             <input type="number" id="${key}_pass_${index}" value="${valPass || ''}" class="form-control form-control-sm" placeholder="Optional" oninput="updateConfigJSON(${index})">
                        </div>
                         <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="${key}_must_pass_${index}" ${checked ? 'checked' : ''} onchange="updateConfigJSON(${index})">
                            <label class="form-check-label small" for="${key}_must_pass_${index}">Must Pass</label>
                        </div>
                    </div>
                </div>
            `;
        }

        function generateSubField(index, idPrefix, label, value = '') {
            return `
                <div class="mb-1 d-flex align-items-center justify-content-between">
                    <label class="small text-muted mb-0">${label}</label>
                    <input type="number" id="${idPrefix}_${index}" value="${value || ''}" class="form-control form-control-sm w-50" placeholder="0" oninput="calculateTotal(${index}); updateConfigJSON(${index})">
                </div>
            `;
        }

        function generatePassField(index, idPrefix, label, value = '') {
            return `
                <div class="col-4">
                    <label class="small text-muted">${label}</label>
                    <input type="number" id="${idPrefix}_${index}" value="${value || ''}" class="form-control form-control-sm" placeholder="0" oninput="updateConfigJSON(${index})">
                </div>
            `;
        }

        function calculateTotal(index) {
            const mode = document.getElementById(`paper_mode_${index}`).value;
            let total = 0;
            const configInput = document.getElementById(`total_marks_${index}`);

            if (mode === 'merged') {
                total += Number(document.getElementById(`cq_${index}`)?.value || 0);
                total += Number(document.getElementById(`mcq_${index}`)?.value || 0);
                total += Number(document.getElementById(`practical_${index}`)?.value || 0);

                // Auto Update Pass Marks (Sum of individual pass marks)
                // Or should we trust the user input? Let's just suggest it if field is empty, OR update always?
                // create.blade.php updates the field. Let's do that.
                let pass = 0;
                pass += Number(document.getElementById(`cq_pass_${index}`)?.value || 0);
                pass += Number(document.getElementById(`mcq_pass_${index}`)?.value || 0);
                pass += Number(document.getElementById(`practical_pass_${index}`)?.value || 0);
                document.getElementById(`pass_marks_${index}`).value = pass;

            } else {
                total += Number(document.getElementById(`first_cq_${index}`)?.value || 0);
                total += Number(document.getElementById(`first_mcq_${index}`)?.value || 0);
                total += Number(document.getElementById(`second_cq_${index}`)?.value || 0);
                total += Number(document.getElementById(`second_mcq_${index}`)?.value || 0);
                total += Number(document.getElementById(`second_practical_${index}`)?.value || 0);

                let pass = 0;
                pass += Number(document.getElementById(`combined_cq_pass_${index}`)?.value || 0);
                pass += Number(document.getElementById(`combined_mcq_pass_${index}`)?.value || 0);
                pass += Number(document.getElementById(`combined_practical_pass_${index}`)?.value || 0);
                document.getElementById(`pass_marks_${index}`).value = pass;
            }
            configInput.value = total;
        }

        function updateConfigJSON(index) {
            const mode = document.getElementById(`paper_mode_${index}`).value;
            const jsonInput = document.getElementById(`config_json_${index}`);
            let data = {};

            if (mode === 'merged') {
                data = {
                    cq: Number(document.getElementById(`cq_${index}`)?.value || 0),
                    mcq: Number(document.getElementById(`mcq_${index}`)?.value || 0),
                    practical: Number(document.getElementById(`practical_${index}`)?.value || 0),
                    pass_config: {
                        cq: Number(document.getElementById(`cq_pass_${index}`)?.value || 0),
                        mcq: Number(document.getElementById(`mcq_pass_${index}`)?.value || 0),
                        practical: Number(document.getElementById(`practical_pass_${index}`)?.value || 0),
                        cq_must_pass: document.getElementById(`cq_must_pass_${index}`)?.checked,
                        mcq_must_pass: document.getElementById(`mcq_must_pass_${index}`)?.checked,
                        practical_must_pass: document.getElementById(`practical_must_pass_${index}`)?.checked,
                    }
                };
            } else {
                data = {
                    mark_distribution: {
                        first_paper: {
                            cq: Number(document.getElementById(`first_cq_${index}`)?.value || 0),
                            mcq: Number(document.getElementById(`first_mcq_${index}`)?.value || 0)
                        },
                        second_paper: {
                            cq: Number(document.getElementById(`second_cq_${index}`)?.value || 0),
                            mcq: Number(document.getElementById(`second_mcq_${index}`)?.value || 0),
                            practical: Number(document.getElementById(`second_practical_${index}`)?.value || 0)
                        }
                    },
                    pass_config: {
                        cq: Number(document.getElementById(`combined_cq_pass_${index}`)?.value || 0),
                        mcq: Number(document.getElementById(`combined_mcq_pass_${index}`)?.value || 0),
                        practical: Number(document.getElementById(`combined_practical_pass_${index}`)?.value || 0)
                    }
                };
            }
            jsonInput.value = JSON.stringify(data);
        }

    </script>

@endsection