<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <section class="content-header">
        <h1>
            <i class="fa fa-gavel"></i> <?php echo $this->lang->line('discipline'); ?> <small><?php echo $this->lang->line('student_fee1'); ?></small>
        </h1>
        <a href="<?php echo base_url(); ?>admin/discipline/create_incident" class="col-md pull-right">Create New Incident</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php echo base_url(); ?>admin/discipline/incident_categories" class="col-md pull-right">Incident Categories</a>
        <b style="padding-left:5px;padding-right:5px;" class="pull-right"> | </b>
        <a href="<?php echo base_url(); ?>admin/discipline/incident_types" class="col-md pull-right">Incident Types</a>
    </section>

    <!-- Main content -->
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <!-- Filter Box -->
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-filter"></i> Filter Incident Reports</h3>
                    </div>
                    <div class="box-body">
                        <form method="get" action="<?php echo base_url(); ?>admin/discipline/incident_reports_list" id="filterForm">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="category_filter">Filter by Category</label>
                                        <select id="category_filter" name="category_filter" class="form-control">
                                            <option value="">All Categories</option>
                                            <?php foreach ($incident_categories as $category) { ?>
                                                <option value="<?php echo $category['id']; ?>" <?php echo ($category_filter == $category['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $category['name']; ?>
                                                </option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="type_filter">Filter by Type</label>
                                        <select id="type_filter" name="type_filter" class="form-control">
                                            <option value="">All Types</option>
                                            <?php foreach ($incident_types as $type) { ?>
                                                <option value="<?php echo $type['id']; ?>" <?php echo ($type_filter == $type['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $type['name']; ?>
                                                </option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="learner_filter">Filter by Learner</label>
                                        <select id="learner_filter" name="learner_filter" class="form-control">
                                            <option value="">All Learners</option>
                                            <?php foreach ($all_students as $student) { ?>
                                                <option value="<?php echo $student['id']; ?>" <?php echo ($learner_filter == $student['id']) ? 'selected' : ''; ?>>
                                                    <?php echo $student['firstname'] . ' ' . $student['lastname'] . ' (' . $student['admission_no'] . ') - ' . $student['class'] . ' ' . $student['section']; ?>
                                                </option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <button type="submit" name="search" value="search_filter" class="btn btn-primary btn-sm checkbox-toggle"><i class="fa fa-search"></i> Search</button>
                                    <button type="button" id="resetFilters" class="btn btn-default btn-sm">Reset</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if (isset($reports_list)) { ?>
                    <?php
                        // Prepare school logo path safely before JavaScript
                        $logoPath = !empty($settinglist[0]['image']) 
                            ? base_url('uploads/school_content/logo/' . $settinglist[0]['image']) 
                            : '';
                        ?>
                <!-- Reports Table -->
                <div class="box box-primary">
                    <div class="box-header ptbnull">
                        <h3 class="box-title titlefix">All Incident Reports</h3>
                        <div class="box-tools pull-right">
                            <?php if ($category_filter || $type_filter || $learner_filter) { ?>
                                <button id="printIncidentBtn" class="btn btn-info btn-sm printInv"  
                                        data-category_filter="<?php echo $category_filter; ?>"  
                                        data-type_filter="<?php echo $type_filter; ?>"                          
                                        data-learner_filter="<?php echo $learner_filter; ?>" 
                                        title="<?php echo $this->lang->line('print'); ?>">
                                    <i class="fa fa-print"></i> Print Report
                                </button>
                            <?php } ?>
                        </div>
                    </div>
                    <div class="box-body">
                        <div class="table-responsive mailbox-messages">
                            <table class="table table-striped table-bordered table-hover example">
                                <thead>
                                    <tr>
                                        <th>Admission No</th>
                                        <th>Learner Name</th>
                                        <th>Class</th>
                                        <th>Section</th>
                                        <th>Incident Type</th>
                                        <th>Incident Category</th>
                                        <th>Incident Date</th>
                                        <th>Reported To</th>
                                        <th>Reported By</th>
                                        <th class="text-right">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($reports_list)) { ?>
                                        <tr>
                                            <td colspan="10" class="text-center text-danger">
                                                No incident reports found matching your filters.
                                            </td>
                                        </tr>
                                    <?php } else {
                                        foreach ($reports_list as $report) { ?>
                                  <tr>
                                                <td><?php echo $report['admission_no']; ?></td>
                                                <td><?php echo $report['firstname'] . ' ' . $report['lastname']; ?></td>
                                                <td><?php echo $report['class']; ?></td>
                                                <td><?php echo $report['section']; ?></td>
                                                <td>
                                                    <span class="label label-warning"><?php echo $report['incident_type']; ?></span>
                                                </td>
                                                <td>
                                                    <span class="label label-info"><?php echo $report['incident_category']; ?></span>
                                                </td>
                                                <td><?php echo date($this->customlib->getSchoolDateFormat(), strtotime($report['incident_date'])); ?></td>
                                                <td><?php echo $report['reported_to']; ?></td>
                                                <td><?php echo $report['reported_by']; ?></td>
                                                 <!-- Hidden data for printing -->
                                                <td style="display:none;" class="description"><?php echo htmlspecialchars($report['description']); ?></td>
                                                <td style="display:none;" class="action_taken"><?php echo htmlspecialchars($report['action_taken'] ?: 'N/A'); ?></td>
                                                <td style="display:none;" class="outcome"><?php echo htmlspecialchars($report['outcome'] ?: 'N/A'); ?></td>

                                                <td class="mailbox-date pull-right">
                                                    <?php if ($this->rbac->hasPrivilege('marks_register', 'can_delete')) { ?>
                                                        
                                                    <?php } ?>
                                                    <button type="button" class="btn btn-info btn-xs view-incident-btn" data-toggle="popover" data-html="true" 
                                                            data-content="
                                                            <div style='min-width: 300px;'>
                                                                <strong>Description:</strong><br><?php echo htmlspecialchars($report['description']); ?><br><br>
                                                                <strong>Action Taken:</strong><br><?php echo htmlspecialchars($report['action_taken'] ?: 'N/A'); ?><br><br>
                                                                <strong>Outcome:</strong><br><?php echo htmlspecialchars($report['outcome'] ?: 'N/A'); ?>
                                                            </div>"
                                                            title="Incident Details - <?php echo $report['firstname'] . ' ' . $report['lastname']; ?>">
                                                        <i class="fa fa-eye"></i> View Details
                                                    </button>
                                                </td>
                                            </tr>

                                        <?php }
                                    } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
    </section>
</div>


<script>
document.getElementById("printIncidentBtn").addEventListener("click", function () {
    let logoPath = "<?php echo $logoPath; ?>";

    let printContent = `
        <div style="text-align:center; padding: 10px; border-bottom: 2px solid #000;">
            ${logoPath ? `<img src="${logoPath}" alt="School Logo" style="height: 90px; margin-bottom: 10px;">` : ''}
            <h2 style="margin: 0; font-weight: bold;"><?php echo $settinglist[0]['name']; ?></h2>
            <p style="margin: 1;"><?php echo $settinglist[0]['address']; ?></p>
            <p><?php echo $this->lang->line('phone'); ?>: <?php echo $settinglist[0]['phone']; ?></p>
            <h4 style="margin-top: 10px; font-weight: bold; text-decoration: underline;">INCIDENT REPORT</h4>
        </div>

        <table border="0" cellspacing="0" cellpadding="5" width="100%">
            <thead>
                <tr>
                    <th>Admission No</th>
                    <th>Learner</th>
                    <th>Class</th>
                    <th>Incident Type</th>
                    <th>Category</th>
                    <th>Date</th>
                    <th>Reported To</th>
                    <th>Reported By</th>
                    <th>Description</th>
                    <th>Action Taken</th>
                    <th>Outcome</th>
                </tr>
            </thead>
            <tbody>
    `;

    document.querySelectorAll("table tbody tr").forEach(function(row) {
        printContent += `
            <tr>
                <td>${row.cells[0].textContent}</td>
                <td>${row.cells[1].textContent}</td>
                <td>${row.cells[2].textContent} ${row.cells[3].textContent}</td> <!-- Class + Section -->
                <td>${row.cells[4].textContent}</td>
                <td>${row.cells[5].textContent}</td>
                <td>${row.cells[6].textContent}</td>
                <td>${row.cells[7].textContent}</td>
                <td>${row.cells[8].textContent}</td>
                <td>${row.querySelector(".description").textContent}</td>
                <td>${row.querySelector(".action_taken").textContent}</td>
                <td>${row.querySelector(".outcome").textContent}</td>
            </tr>
        `;
    });

    printContent += `</tbody></table>
    <!-- Footer -->
    <div style="text-align:center; margin-top: 60px; font-size: 10px; color: #555;">
        &copy; ${new Date().getFullYear()} Melsoft Pvt Ltd. All rights reserved.
    </div>`;


    // Open print window
    let printWindow = window.open('', '', 'width=900,height=1000');
   printWindow.document.write(`
    <html>
        <head>
            <title>Incident Report</title>
            <base href="<?php echo base_url(); ?>">
            <style>
                @page { size: A4; margin: 10mm; }
                body { font-family: Arial, sans-serif; }

                table { 
                    border-collapse: collapse; 
                    width: 100%; 
                    font-size: 12px; 
                }

                th { 
                    font-weight: bold; 
                    text-align: left; 
                    padding: 6px; 
                    background-color: #f2f2f2; /* Light grey header */
                    border-bottom: 2px solid #000; /* optional subtle border under header */
                }

                td { 
                    padding: 6px; 
                    /* Optional: border-bottom: 1px solid #ccc; */ 
                }

                /* Striped rows */
                tbody tr:nth-child(even) { 
                    background-color: #f9f9f9; 
                }

                img { 
                    max-width: 100%; 
                    height: auto; 
                }
            </style>
        </head>
        <body>${printContent}</body>
    </html>
`);
printWindow.document.close();

    // Trigger print AFTER images load
    printWindow.onload = function () {
        printWindow.focus();
        printWindow.print(); // This automatically opens Print dialog (Printer or Save as PDF)
    };
});

$(document).ready(function () {
      $('.view-incident-btn').popover({
        placement: 'auto',  // Automatically choose best placement
        trigger: 'focus',    // Works better on mobile
        html: true,
        container: 'body'
    });
// Close popover when clicking outside
    $('body').on('click touchstart', function (e) {
        if ($(e.target).data('toggle') !== 'popover' && $(e.target).parents('.popover').length === 0) {
            $('.view-incident-btn').popover('hide');
        }
    });

    $('#resetFilters').on('click', function() {
        $('#category_filter, #type_filter, #learner_filter').val('');
        $('#filterForm').submit();
    });
});

 $(document).ready(function () {
        // Initialize popovers
        $('.view-incident-btn').popover({
            placement: 'left',
            trigger: 'click',
            container: 'body'
        });

        // Close popover when clicking elsewhere
        $('body').on('click', function (e) {
            if ($(e.target).data('toggle') !== 'popover' && $(e.target).parents('.popover.in').length === 0) { 
                $('.view-incident-btn').popover('hide');
            }
        });

        // Reset filters
        $('#resetFilters').on('click', function() {
            $('#category_filter').val('');
            $('#type_filter').val('');
            $('#learner_filter').val('');
            $('#filterForm').submit();
        });
    });
</script>


<style>
.label {
    font-size: 11px;
    padding: 3px 8px;
}
.popover {
    max-width: 400px;
}
</style>