<section class="panel">
    <div class="tabs-custom">
        <ul class="nav nav-tabs">
            <li class="active">
                <a href="#list" data-toggle="tab"><i class="fas fa-star"></i> <?=translate('rating_list')?></a>
            </li>
            <?php if (get_permission('subject', 'is_add')): ?>
                <li>
                    <a href="#create" data-toggle="tab"><i class="far fa-edit"></i> <?=translate('create_rating')?></a>
                </li>
            <?php endif; ?>
        </ul>

        <div class="tab-content">
            <!-- Comment List Section -->
            <div id="list" class="tab-pane active">
                <table class="table table-bordered table-hover mb-none table-export">
                    <thead>
                        <tr>
                            <th width="60"><?=translate('sl')?></th>
                            <th><?=translate('branch')?></th>
                            <th><?=translate('subject')?></th>
                            <th><?=translate('rating')?></th>
                            <th><?=translate('comment_code')?></th>
                            <th><?=translate('action')?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $count = 1;
                        foreach($subjectlist as $row):
                        ?>
                        <tr>
                            <td><?php echo $count++; ?></td>
                            <td><?php echo $row['branch_name']; ?></td>
                            <td><?php echo $row['subject_name']; ?></td>
                            <td><?php echo $row['comment']; ?></td>
                            <td><?php echo $row['comment_code']; ?></td>
                            <td class="action">
                                <?php if (get_permission('subject', 'is_edit')): ?>
                                    <a href="<?php echo base_url('comments/edit/' . $row['id']);?>" class="btn btn-circle btn-default icon">
                                        <i class="fas fa-pen-nib"></i>
                                    </a>
                                <?php endif; ?>
                                <?php if (get_permission('subject', 'is_delete')): ?>
                                    <?php echo btn_delete('comments/delete/' . $row['id']);?>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach;?>
                    </tbody>
                </table>
            </div>

            <!-- Create Comment Section -->
            <?php if (get_permission('subject', 'is_add')): ?>
                <div class="tab-pane" id="create">
                    <?php echo form_open('comments/save', array('class' => 'form-horizontal form-bordered frm-submit')); ?>

                    <?php if (is_superadmin_loggedin()): ?>
    <div class="form-group">
        <label class="control-label col-md-3"><?= translate('branch') ?> <span class="required">*</span></label>
        <div class="col-md-6">
            <?php
                $arrayBranch = $this->app_lib->getSelectList('branch');
                echo form_dropdown("branch_id", $arrayBranch, set_value('branch_id'), 
                    "class='form-control' id='branch_id' data-width='100%' 
                    data-plugin-selectTwo data-minimum-results-for-search='Infinity'"
                );
            ?>
            <span class="error"></span>
        </div>
    </div>
<?php else: ?>
    <input type="hidden" name="branch_id" id="branch_id" value="<?= get_loggedin_branch_id(); ?>">
<?php endif; ?>

                    <div class="form-group row">
                        <label class="col-md-3 control-label"><?= translate('subject') ?> <span class="required">*</span></label>
                        <div class="col-md-6">
                            <?php
                            $arraySubject = array("" => translate('select'));
                            echo form_dropdown("subject_id", $arraySubject, set_value('subject_id'), 
                                "class='form-control' id='subject_id' required data-plugin-selectTwo data-width='100%' data-minimum-results-for-search='Infinity'"
                            );
                            ?>
                            <span class="error"></span>
                        </div>
                    </div>
					<input type="hidden" name="comment_id" id="comment_id">


                    <div class="form-group row">
                        <label class="col-md-3 control-label"><?=translate('comment')?> <span class="required">*</span></label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" name="comment" id="comment" oninput="generateCommentCode()" />
                            <span class="error"></span>
                        </div>
                    </div>

                    <div class="form-group row">
                        <label class="col-md-3 control-label"><?=translate('comment_code')?> <span class="required">*</span></label>
                        <div class="col-md-6">
                            <input type="text" class="form-control" name="comment_code" id="comment_code" readonly />
                            <span class="error"></span>
                        </div>
                    </div>

                    <footer class="panel-footer">
                        <div class="row">
                            <div class="col-md-offset-3 col-md-2">
                                <button type="submit" class="btn btn-default btn-block" data-loading-text="<i class='fas fa-spinner fa-spin'></i> Processing">
                                    <i class="fas fa-plus-circle"></i> <?=translate('save')?>
                                </button>
                            </div>
                        </div>
                    </footer>

                    <?php echo form_close(); ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<script>
  function generateCommentCode() {
    const commentInput = document.getElementById('comment').value.trim();
    const commentCodeField = document.getElementById('comment_code');
    
    if (commentInput.length >= 2) {
      // Take the first two letters of the comment
      const prefix = commentInput.substring(0, 2).toUpperCase();
      // Generate a random 4-digit number
      const randomNumber = Math.floor(1000 + Math.random() * 9000);
      // Combine the prefix and the random number
      commentCodeField.value = `${prefix}-${randomNumber}`;
    } else {
      commentCodeField.value = ''; // Clear if input is less than 2 characters
    }
  }

  $(document).ready(function () {
    $("#branch_id").change(function () {
        var branch_id = $(this).val();
        console.log("Selected Branch ID: ", branch_id);

        if (branch_id) {
            $.ajax({
                url: "<?= base_url('comments/getSubjectsByBranch') ?>",
                type: "POST",
                data: {branch_id: branch_id},
                dataType: "json",
                success: function (response) {
                    console.log("Response from server:", response);
                    
                    var subjectDropdown = $("#subject_id");
                    subjectDropdown.empty();
                    subjectDropdown.append('<option value=""><?= translate('select') ?></option>');

                    if (response.error) {
                        alert(response.error);
                        return;
                    }

                    $.each(response, function (key, value) {
                        subjectDropdown.append('<option value="' + key + '">' + value + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                    console.error("AJAX Error:", error);
                }
            });
        } else {
            $("#subject_id").html('<option value=""><?= translate('select') ?></option>');
        }
    });
});





$(document).ready(function () {
    function loadSubjects(branch_id) {
        console.log("Selected Branch ID: ", branch_id);
        if (branch_id) {
            $.ajax({
                url: "<?= base_url('comments/getSubjectsByBranch') ?>",
                type: "POST",
                data: {branch_id: branch_id},
                dataType: "json",
                success: function (response) {
                    console.log("Response from server:", response);
                    
                    var subjectDropdown = $("#subject_id");
                    subjectDropdown.empty();
                    subjectDropdown.append('<option value=""><?= translate('select') ?></option>');

                    if (response.error) {
                        alert(response.error);
                        return;
                    }

                    $.each(response, function (key, value) {
                        subjectDropdown.append('<option value="' + key + '">' + value + '</option>');
                    });
                },
                error: function (xhr, status, error) {
                    console.error("AJAX Error:", error);
                }
            });
        } else {
            $("#subject_id").html('<option value=""><?= translate('select') ?></option>');
        }
    }

    // Auto-load subjects if branch_id is pre-set (for non-superadmins)
    var initial_branch_id = $("#branch_id").val();
    if (initial_branch_id) {
        loadSubjects(initial_branch_id);
    }

    // On branch_id change (for superadmin)
    $("#branch_id").change(function () {
        var branch_id = $(this).val();
        loadSubjects(branch_id);
    });
});





  
</script>
