<?php
/**
 * Shortcode generator page.
 */

if (! defined('ABSPATH')) {
        exit;
}

global $wpdb;

class ASTGDRMSYS_Shortcode_Generator
{
        /** @var \wpdb */
        private $wpdb;

        /** @var string */
        private $prefix;

        /** @var array */
        private $selections = array(
                'class'      => '',
                'department' => '',
                'section'    => '',
                'exam'       => '',
        );

        /** @var bool */
        private $require_registration = false;

        /**
         * Constructor.
         *
         * @param \wpdb $wpdb WordPress database object.
         */
        public function __construct($wpdb)
        {
                $this->wpdb   = $wpdb;
                $this->prefix = $wpdb->prefix;
                $this->capture_request();
        }

        /**
         * Render the generator page.
         */
        public function render(): void
        {
                $classes     = $this->get_classes();
                $departments = $this->get_departments();
                $sections    = $this->get_sections();
                $exams       = $this->get_exams();
                $shortcode   = $this->build_shortcode();

                $page_data = array(
                        'classes'     => $classes,
                        'departments' => $departments,
                        'sections'    => $sections,
                        'exams'       => $exams,
                );
                ?>
                <div class="wrap astgdrmsys-shortcode-page astgdrmsys-premium-wrap">
			<div class="premium-page-header">
				<div class="page-header-text">
					<h1><?php echo esc_html__('Shortcode Generator', 'result-management-system-for-institutions'); ?></h1>
					<p><?php echo esc_html__('Copy the base shortcode or prefill values to hide fields on the public result form.', 'result-management-system-for-institutions'); ?></p>
				</div>
			</div>

                        <div class="astgdrmsys-shortcode-card">
                                <h2><?php echo esc_html__('Base shortcode', 'result-management-system-for-institutions'); ?></h2>
                                <p><?php echo esc_html__('Use this shortcode anywhere to display the search form.', 'result-management-system-for-institutions'); ?></p>
                                <div class="astgdrmsys-shortcode-row">
                                        <input type="text" readonly id="astgdrmsys-base-shortcode" value="[astgdrmsys_show_result]">
                                        <button type="button" class="button" data-copy-target="astgdrmsys-base-shortcode">
                                                <?php echo esc_html__('Copy shortcode', 'result-management-system-for-institutions'); ?>
                                        </button>
                                </div>
                        </div>

                        <div class="astgdrmsys-shortcode-card">
                                <h2><?php echo esc_html__('Generate shortcode with preset values', 'result-management-system-for-institutions'); ?></h2>
                                <p><?php echo esc_html__('Preselected values hide those fields on the result form.', 'result-management-system-for-institutions'); ?></p>
                                <table class="form-table">
                                        <tr>
                                                <th scope="row">
                                                        <label for="astgdrmsys-shortcode-class"><?php echo esc_html__('Class', 'result-management-system-for-institutions'); ?></label>
                                                </th>
                                                <td>
                                                        <select id="astgdrmsys-shortcode-class" name="astgdrmsys-shortcode-class">
                                                                <option value=""><?php echo esc_html__('No preset', 'result-management-system-for-institutions'); ?></option>
                                                                <?php foreach ($classes as $class) : ?>
                                                                        <option value="<?php echo esc_attr($class['id']); ?>" <?php selected((string) $this->selections['class'], (string) $class['id']); ?>>
                                                                                <?php echo esc_html($class['class']); ?>
                                                                        </option>
                                                                <?php endforeach; ?>
                                                        </select>
                                                </td>
                                        </tr>
                                        <tr>
                                                <th scope="row">
                                                        <label for="astgdrmsys-shortcode-department"><?php echo esc_html__('Department', 'result-management-system-for-institutions'); ?></label>
                                                </th>
                                                <td>
                                                        <select id="astgdrmsys-shortcode-department" name="astgdrmsys-shortcode-department">
                                                                <option value=""><?php echo esc_html__('No preset', 'result-management-system-for-institutions'); ?></option>
                                                                <?php foreach ($departments as $department) : ?>
                                                                        <option value="<?php echo esc_attr($department['id']); ?>" <?php selected((string) $this->selections['department'], (string) $department['id']); ?>>
                                                                                <?php echo esc_html($department['department']); ?>
                                                                        </option>
                                                                <?php endforeach; ?>
                                                        </select>
                                                </td>
                                        </tr>
                                        <tr>
                                                <th scope="row">
                                                        <label for="astgdrmsys-shortcode-section"><?php echo esc_html__('Section', 'result-management-system-for-institutions'); ?></label>
                                                </th>
                                                <td>
                                                        <select id="astgdrmsys-shortcode-section" name="astgdrmsys-shortcode-section">
                                                                <option value=""><?php echo esc_html__('No preset', 'result-management-system-for-institutions'); ?></option>
                                                                <?php foreach ($sections as $section) : ?>
                                                                        <option value="<?php echo esc_attr($section['id']); ?>" data-class="<?php echo esc_attr($section['class_id']); ?>" data-department="<?php echo esc_attr($section['department']); ?>" <?php selected((string) $this->selections['section'], (string) $section['id']); ?>>
                                                                                <?php echo esc_html($section['section']); ?>
                                                                        </option>
                                                                <?php endforeach; ?>
                                                        </select>
                                                </td>
                                        </tr>
                                        <tr>
                                                <th scope="row">
                                                        <label for="astgdrmsys-shortcode-exam"><?php echo esc_html__('Exam name', 'result-management-system-for-institutions'); ?></label>
                                                </th>
                                                <td>
                                                        <select id="astgdrmsys-shortcode-exam" name="astgdrmsys-shortcode-exam">
                                                                <option value=""><?php echo esc_html__('No preset', 'result-management-system-for-institutions'); ?></option>
                                                                <?php foreach ($exams as $exam) :
                                                                        $value = empty($exam['exam_year_id']) ? $exam['id'] : $exam['id'] . ',' . $exam['exam_year_id'];
                                                                        ?>
                                                                        <option value="<?php echo esc_attr($value); ?>" data-class="<?php echo esc_attr($exam['class_id']); ?>" data-department-name="<?php echo esc_attr($exam['department']); ?>" <?php selected((string) $this->selections['exam'], (string) $value); ?>>
                                                                                <?php
                                                                                $label = $exam['exam_name'];
                                                                                if (! empty($exam['exam_year'])) {
                                                                                        $label .= ' - ' . $exam['exam_year'];
                                                                                }
                                                                                echo esc_html($label);
                                                                                ?>
                                                                        </option>
                                                                <?php endforeach; ?>
                                                        </select>
                                                </td>
                                        </tr>
                                        <tr>
                                                <th scope="row">
                                                        <label for="astgdrmsys-shortcode-require-registration"><?php echo esc_html__('Require registration number', 'result-management-system-for-institutions'); ?></label>
                                                </th>
                                                <td>
                                                        <label>
                                                                <input type="checkbox" id="astgdrmsys-shortcode-require-registration" name="astgdrmsys-shortcode-require-registration" value="1" <?php checked($this->require_registration); ?>>
                                                                <?php echo esc_html__('This will enforce user to put both their roll number and registration number to get their result.', 'result-management-system-for-institutions'); ?>
                                                        </label>
                                                </td>
                                        </tr>
                                </table>

                                <div class="astgdrmsys-shortcode-row">
                                        <label for="astgdrmsys-generated-shortcode" class="screen-reader-text">
                                                <?php echo esc_html__('Generated shortcode', 'result-management-system-for-institutions'); ?>
                                        </label>
                                        <input type="text" readonly id="astgdrmsys-generated-shortcode" value="<?php echo esc_attr($shortcode); ?>">
                                        <button type="button" class="button button-primary" data-copy-target="astgdrmsys-generated-shortcode">
                                                <?php echo esc_html__('Copy generated shortcode', 'result-management-system-for-institutions'); ?>
                                        </button>
                                </div>
                                <p class="description">
                                        <?php echo esc_html__('Save your selections with the copy buttons above. Presets will hide matching fields on the public result search.', 'result-management-system-for-institutions'); ?>
                                </p>
                        </div>
                </div>
                <script>
                (function() {
                        const data = <?php echo wp_json_encode($page_data); ?>;
                        const selections = {
                                class: document.getElementById('astgdrmsys-shortcode-class'),
                                department: document.getElementById('astgdrmsys-shortcode-department'),
                                section: document.getElementById('astgdrmsys-shortcode-section'),
                                exam: document.getElementById('astgdrmsys-shortcode-exam'),
                        };

                        const requireRegistration = document.getElementById('astgdrmsys-shortcode-require-registration');

                        const copyButtons = document.querySelectorAll('[data-copy-target]');
                        copyButtons.forEach((button) => {
                                button.addEventListener('click', () => {
                                        const target = document.getElementById(button.getAttribute('data-copy-target'));
                                        if (!target) {
                                                return;
                                        }

                                        target.select();
                                        target.setSelectionRange(0, target.value.length);
                                        document.execCommand('copy');

                                        button.classList.add('astgdrmsys-copied');
                                        setTimeout(() => button.classList.remove('astgdrmsys-copied'), 1200);
                                });
                        });

                        const departmentMap = data.departments.reduce((map, department) => {
                                map[department.id] = department.department;
                                return map;
                        }, {});

                        function populateDepartments() {
                                const previous = selections.department.value;
                                selections.department.innerHTML = '<option value="">' + <?php echo wp_json_encode(esc_html__('No preset', 'result-management-system-for-institutions')); ?> + '</option>';

                                data.departments
                                        .forEach((item) => {
                                                const option = document.createElement('option');
                                                option.value = item.id;
                                                option.textContent = item.department;
                                                selections.department.appendChild(option);
                                        });

                                if (previous && selections.department.querySelector(`option[value="${previous}"]`)) {
                                        selections.department.value = previous;
                                } else {
                                        selections.department.value = '';
                                }
                        }

                        function populateSections() {
                                const classId = parseInt(selections.class.value || '0', 10);
                                const deptId = parseInt(selections.department.value || '0', 10);
                                const previous = selections.section.value;
                                selections.section.innerHTML = '<option value="">' + <?php echo wp_json_encode(esc_html__('No preset', 'result-management-system-for-institutions')); ?> + '</option>';

                                data.sections
                                        .filter((item) => {
                                                const classMatch = !classId || parseInt(item.class_id, 10) === classId;
                                                const deptMatch = !deptId || parseInt(item.department, 10) === deptId;
                                                return classMatch && deptMatch;
                                        })
                                        .forEach((item) => {
                                                const option = document.createElement('option');
                                                option.value = item.id;
                                                option.textContent = item.section;
                                                option.dataset.class = item.class_id;
                                                option.dataset.department = item.department;
                                                selections.section.appendChild(option);
                                        });

                                if (previous && selections.section.querySelector(`option[value="${previous}"]`)) {
                                        selections.section.value = previous;
                                } else {
                                        selections.section.value = '';
                                }
                        }

                        function populateExams() {
                                const classId = parseInt(selections.class.value || '0', 10);
                                const deptId = parseInt(selections.department.value || '0', 10);
                                const departmentName = deptId ? departmentMap[deptId] || '' : '';
                                const previous = selections.exam.value;
                                selections.exam.innerHTML = '<option value="">' + <?php echo wp_json_encode(esc_html__('No preset', 'result-management-system-for-institutions')); ?> + '</option>';

                                data.exams
                                        .filter((item) => {
                                                const classMatch = !classId || parseInt(item.class_id, 10) === classId;
                                                const examDepartmentId = parseInt(item.department || '0', 10);
                                                const deptMatch = !deptId || examDepartmentId === deptId || item.department === departmentName;
                                                return classMatch && deptMatch;
                                        })
                                        .forEach((item) => {
                                                const option = document.createElement('option');
                                                option.value = item.exam_year_id ? `${item.id},${item.exam_year_id}` : item.id;
                                                option.dataset.class = item.class_id;
                                                option.dataset.departmentName = item.department || '';
                                                option.textContent = item.exam_year ? `${item.exam_name} - ${item.exam_year}` : item.exam_name;
                                                selections.exam.appendChild(option);
                                        });

                                if (previous && selections.exam.querySelector(`option[value="${previous}"]`)) {
                                        selections.exam.value = previous;
                                } else {
                                        selections.exam.value = '';
                                }
                        }

                        function buildShortcode() {
                                const attributes = [];
                                const classValue = selections.class.value;
                                const deptValue = selections.department.value;
                                const sectionValue = selections.section.value;
                                const examValue = selections.exam.value;

                                if (classValue) {
                                        attributes.push(`sclass="${classValue}"`);
                                }

                                if (deptValue) {
                                        attributes.push(`sdepartment="${deptValue}"`);
                                }

                                if (sectionValue) {
                                        attributes.push(`ssection="${sectionValue}"`);
                                }

                                if (examValue) {
                                        attributes.push(`s_exam_name="${examValue}"`);
                                }

                                if (requireRegistration && requireRegistration.checked) {
                                        attributes.push('require_registration="1"');
                                }

                                const shortcode = `[astgdrmsys_show_result${attributes.length ? ' ' + attributes.join(' ') : ''}]`;
                                const output = document.getElementById('astgdrmsys-generated-shortcode');
                                if (output) {
                                        output.value = shortcode;
                                }
                        }

                        function handleChange() {
                                populateDepartments();
                                populateSections();
                                populateExams();
                                buildShortcode();
                        }

                        selections.class.addEventListener('change', handleChange);
                        selections.department.addEventListener('change', () => {
                                populateSections();
                                populateExams();
                                buildShortcode();
                        });
                        selections.section.addEventListener('change', buildShortcode);
                        selections.exam.addEventListener('change', buildShortcode);
                        if (requireRegistration) {
                                requireRegistration.addEventListener('change', buildShortcode);
                        }

                        populateDepartments();
                        populateSections();
                        populateExams();
                        buildShortcode();
                })();
                </script>
                <style>
                        .astgdrmsys-shortcode-page .astgdrmsys-shortcode-card {
                                background: #fff;
                                border: 1px solid #ccd0d4;
                                border-radius: 8px;
                                margin: 20px 0;
                                padding: 20px;
                        }
                        .astgdrmsys-shortcode-row {
                                display: flex;
                                gap: 10px;
                                align-items: center;
                        }
                        .astgdrmsys-shortcode-row input[type="text"] {
                                width: 100%;
                                max-width: 520px;
                        }
                        .astgdrmsys-shortcode-card .description {
                                margin-top: 10px;
                                color: #50575e;
                        }
                        .astgdrmsys-shortcode-row .button.astgdrmsys-copied {
                                box-shadow: 0 0 0 1px #00a32a;
                        }
                </style>
                <?php
        }

        /**
         * Capture selected values from the request.
         */
        private function capture_request(): void
        {
                if (empty($_POST)) {
                        return;
                }

                $this->selections['class']      = isset($_POST['astgdrmsys-shortcode-class']) ? sanitize_text_field(wp_unslash($_POST['astgdrmsys-shortcode-class'])) : '';
                $this->selections['department'] = isset($_POST['astgdrmsys-shortcode-department']) ? sanitize_text_field(wp_unslash($_POST['astgdrmsys-shortcode-department'])) : '';
                $this->selections['section']    = isset($_POST['astgdrmsys-shortcode-section']) ? sanitize_text_field(wp_unslash($_POST['astgdrmsys-shortcode-section'])) : '';
                $this->selections['exam']       = isset($_POST['astgdrmsys-shortcode-exam']) ? sanitize_text_field(wp_unslash($_POST['astgdrmsys-shortcode-exam'])) : '';
                $this->require_registration     = ! empty($_POST['astgdrmsys-shortcode-require-registration']);
        }

        /**
         * Build the shortcode string.
         */
        private function build_shortcode(): string
        {
                $attributes = array();

                foreach (array('sclass' => 'class', 'sdepartment' => 'department', 'ssection' => 'section', 's_exam_name' => 'exam') as $attribute => $key) {
                        if (! empty($this->selections[$key])) {
                                $attributes[] = sprintf('%s="%s"', $attribute, esc_attr($this->selections[$key]));
                        }
                }

                if ($this->require_registration) {
                        $attributes[] = 'require_registration="1"';
                }

                return '[astgdrmsys_show_result' . (empty($attributes) ? '' : ' ' . implode(' ', $attributes)) . ']';
        }

        /**
         * Fetch classes.
         */
        private function get_classes(): array
        {
                $table = esc_sql($this->prefix . 'astgdrmsys_class');
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
                return $this->wpdb->get_results("SELECT id, class FROM {$table} ORDER BY class ASC", ARRAY_A);
        }

        /**
         * Fetch global departments.
         */
        private function get_departments(): array
        {
                $department_table = esc_sql($this->prefix . 'astgdrmsys_department');
                $sql              = "SELECT id, department FROM {$department_table} ORDER BY department ASC";
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
                return $this->wpdb->get_results($sql, ARRAY_A);
        }

        /**
         * Fetch sections with class and department references.
         */
        private function get_sections(): array
        {
                $section_table    = esc_sql($this->prefix . 'astgdrmsys_section');
                $department_table = esc_sql($this->prefix . 'astgdrmsys_department');
                $class_table      = esc_sql($this->prefix . 'astgdrmsys_class');
                $sql              = "SELECT s.id, s.section, s.department, c.id AS class_id, c.class FROM {$section_table} s LEFT JOIN {$class_table} c ON s.classname = c.class ORDER BY s.section ASC";
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery
                return $this->wpdb->get_results($sql, ARRAY_A);
        }

        /**
         * Fetch exams.
         */
        private function get_exams(): array
        {
                $table = esc_sql($this->prefix . 'astgdrmsys_exam_name');
                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.DirectQuery
                return $this->wpdb->get_results("SELECT id, exam_name, exam_year, exam_year_id, class_id, department FROM {$table} ORDER BY exam_year DESC, exam_name ASC", ARRAY_A);
        }
}

if (! ($wpdb instanceof wpdb)) {
        echo '<div class="notice notice-error"><p>' . esc_html__('Database connection is not available.', 'result-management-system-for-institutions') . '</p></div>';
        return;
}

$generator = new ASTGDRMSYS_Shortcode_Generator($wpdb);
$generator->render();
