<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include 'includes/styles.php'; ?>
        <title>Timetable Conflicts | <?php echo $school_name; ?></title>

        <?php
        $module_name = 'Timetable';
        include "check-admin-privilege.php";

        ?>
        <style>
            .conflict-card {
                background: white;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 15px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                border-left: 5px solid;
                transition: transform 0.2s;
            }
            .conflict-card:hover {
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,0,0,0.15);
            }
            .conflict-card.teacher-clash { border-color: #dc3545; }
            .conflict-card.room-clash { border-color: #ffc107; }
            .conflict-card.resolved { border-color: #28a745; opacity: 0.7; }

            .conflict-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 15px;
            }
            .conflict-type {
                display: inline-block;
                padding: 5px 15px;
                border-radius: 20px;
                font-size: 0.9rem;
                font-weight: 600;
            }
            .type-teacher { background: #f8d7da; color: #721c24; }
            .type-room { background: #fff3cd; color: #856404; }
            .type-resolved { background: #d4edda; color: #155724; }

            .conflict-details {
                background: #f8f9fa;
                padding: 15px;
                border-radius: 6px;
                margin: 15px 0;
            }
            .conflict-entry {
                display: flex;
                justify-content: space-between;
                padding: 10px;
                background: white;
                border-radius: 4px;
                margin: 8px 0;
                border-left: 3px solid #007bff;
            }
            .stats-card {
                text-align: center;
                padding: 20px;
                background: white;
                border-radius: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            .stats-number {
                font-size: 2.5rem;
                font-weight: bold;
                margin: 10px 0;
            }
            .stats-label {
                color: #666;
                font-size: 0.9rem;
            }
            .scan-button {
                padding: 15px 30px;
                font-size: 1.1rem;
                border-radius: 8px;
                box-shadow: 0 4px 8px rgba(0,123,255,0.3);
            }
            .filter-section {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Timetable Conflicts</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item">Timetable</li>
                                <li class="breadcrumb-item active">Conflicts</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Scan Section -->
                    <div class="row mb-4">
                        <div class="col-md-12 text-center">
                            <button class="btn btn-primary scan-button" id="scan-conflicts-btn">
                                <i class="fas fa-search"></i> Scan for Conflicts
                            </button>
                            <p class="text-muted mt-2">Click to check all timetable entries for scheduling conflicts</p>
                        </div>
                    </div>

                    <!-- Statistics -->
                    <div class="row" id="stats-section" style="display:none;">
                        <div class="col-lg-3 col-md-6">
                            <div class="stats-card" style="border-top: 4px solid #dc3545;">
                                <i class="fas fa-exclamation-circle" style="font-size: 2rem; color: #dc3545;"></i>
                                <div class="stats-number" style="color: #dc3545;" id="total-conflicts">0</div>
                                <div class="stats-label">Total Conflicts</div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="stats-card" style="border-top: 4px solid #dc3545;">
                                <i class="fas fa-user-times" style="font-size: 2rem; color: #dc3545;"></i>
                                <div class="stats-number" style="color: #dc3545;" id="teacher-conflicts">0</div>
                                <div class="stats-label">Teacher Conflicts</div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="stats-card" style="border-top: 4px solid #ffc107;">
                                <i class="fas fa-door-closed" style="font-size: 2rem; color: #ffc107;"></i>
                                <div class="stats-number" style="color: #ffc107;" id="room-conflicts">0</div>
                                <div class="stats-label">Room Conflicts</div>
                            </div>
                        </div>

                        <div class="col-lg-3 col-md-6">
                            <div class="stats-card" style="border-top: 4px solid #28a745;">
                                <i class="fas fa-check-circle" style="font-size: 2rem; color: #28a745;"></i>
                                <div class="stats-number" style="color: #28a745;" id="resolved-conflicts">0</div>
                                <div class="stats-label">Resolved</div>
                            </div>
                        </div>
                    </div>

                    <!-- Filter Section -->
                    <div class="filter-section" id="filter-section" style="display:none;">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Filter by Type</label>
                                    <select class="form-control" id="filter-type">
                                        <option value="all">All Conflicts</option>
                                        <option value="teacher_clash">Teacher Conflicts</option>
                                        <option value="room_clash">Room Conflicts</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>Filter by Status</label>
                                    <select class="form-control" id="filter-status">
                                        <option value="unresolved">Unresolved Only</option>
                                        <option value="all">All</option>
                                        <option value="resolved">Resolved Only</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label>&nbsp;</label>
                                    <button class="btn btn-primary btn-block" id="apply-filter-btn">
                                        <i class="fas fa-filter"></i> Apply Filter
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Conflicts List -->
                    <div id="conflicts-container">
                        <!-- Conflicts will be loaded here -->
                    </div>

                </div>
            </section>

        </div>

        <?php include "includes/footer.php"; ?>
        <!-- Resolve Conflict Modal -->
        <div class="modal fade" id="resolveModal" tabindex="-1">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header bg-success text-white">
                        <h5 class="modal-title">Mark Conflict as Resolved</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <form id="resolve-form">
                        <input type="hidden" id="conflict-id" name="conflict_id">
                        <div class="modal-body">
                            <div class="form-group">
                                <label>Resolution Notes</label>
                                <textarea class="form-control" name="resolution_notes" rows="4" placeholder="Explain how this conflict was resolved..."></textarea>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-check"></i> Mark as Resolved
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
            let allConflicts = [];
            let filteredConflicts = [];

            $(document).ready(function() {
                // Scan for conflicts
                $('#scan-conflicts-btn').on('click', function() {
                    scanForConflicts();
                });

                // Apply filters
                $('#apply-filter-btn').on('click', function() {
                    applyFilters();
                });

                // Resolve form submission
                $('#resolve-form').on('submit', function(e) {
                    e.preventDefault();
                    resolveConflict();
                });
            });

            function scanForConflicts() {
                $('#scan-conflicts-btn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Scanning...');

                $.ajax({
                    url: 'scan-timetable-conflicts.php',
                    type: 'POST',
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            allConflicts = response.conflicts;
                            filteredConflicts = allConflicts;
                            displayStatistics(response.statistics);
                            displayConflicts(allConflicts);
                            $('#stats-section').show();
                            $('#filter-section').show();
                        } else {
                            alert('Error scanning for conflicts');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    },
                    complete: function() {
                        $('#scan-conflicts-btn').prop('disabled', false).html('<i class="fas fa-search"></i> Scan for Conflicts');
                    }
                });
            }

            function displayStatistics(stats) {
                $('#total-conflicts').text(stats.total);
                $('#teacher-conflicts').text(stats.teacher_clash);
                $('#room-conflicts').text(stats.room_clash);
                $('#resolved-conflicts').text(stats.resolved);
            }

            function displayConflicts(conflicts) {
                let html = '';

                if(conflicts.length === 0) {
                    html = `<div class="alert alert-success text-center" style="padding: 40px;">
            <i class="fas fa-check-circle" style="font-size: 4rem; color: #28a745;"></i>
            <h4 style="margin-top: 20px;">No Conflicts Found!</h4>
            <p class="text-muted">Your timetable is conflict-free.</p>
        </div>`;
                } else {
                    conflicts.forEach(conflict => {
                        const cardClass = conflict.is_resolved == 1 ? 'resolved' :
                            (conflict.conflict_type === 'teacher_clash' ? 'teacher-clash' : 'room-clash');

                        const typeClass = conflict.is_resolved == 1 ? 'type-resolved' :
                            (conflict.conflict_type === 'teacher_clash' ? 'type-teacher' : 'type-room');

                        const icon = conflict.conflict_type === 'teacher_clash' ? 'fa-user-times' : 'fa-door-closed';

                        const typeName = conflict.conflict_type === 'teacher_clash' ? 'Teacher Conflict' : 'Room Conflict';

                        html += `
                <div class="conflict-card ${cardClass}" data-type="${conflict.conflict_type}" data-resolved="${conflict.is_resolved}">
                    <div class="conflict-header">
                        <div>
                            <i class="fas ${icon}" style="font-size: 1.5rem; margin-right: 10px;"></i>
                            <span class="conflict-type ${typeClass}">${typeName}</span>
                            ${conflict.is_resolved == 1 ? '<span class="badge badge-success ml-2">Resolved</span>' : ''}
                        </div>
                        <div>
                            ${conflict.is_resolved == 0 ? `
                                <button class="btn btn-sm btn-success resolve-conflict" data-id="${conflict.id}">
                                    <i class="fas fa-check"></i> Mark Resolved
                                </button>
                            ` : `
                                <small class="text-muted">
                                    Resolved by ${conflict.resolved_by || 'System'}<br>
                                    ${conflict.resolved_at ? new Date(conflict.resolved_at).toLocaleDateString() : ''}
                                </small>
                            `}
                        </div>
                    </div>

                    <div class="conflict-details">
                        <strong><i class="fas fa-calendar-day"></i> ${conflict.day_name} - ${conflict.period_name}</strong>
                        <p style="margin: 10px 0; color: #555;">${conflict.conflict_description}</p>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="conflict-entry">
                                    <div>
                                        <strong>${conflict.class1_name} - ${conflict.section1_name}</strong><br>
                                        <small>${conflict.subject1_name}</small><br>
                                        <small class="text-muted">Teacher: ${conflict.teacher1_name}</small>
                                        ${conflict.room1 ? `<br><small class="text-muted">Room: ${conflict.room1}</small>` : ''}
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="conflict-entry">
                                    <div>
                                        <strong>${conflict.class2_name} - ${conflict.section2_name}</strong><br>
                                        <small>${conflict.subject2_name}</small><br>
                                        <small class="text-muted">Teacher: ${conflict.teacher2_name}</small>
                                        ${conflict.room2 ? `<br><small class="text-muted">Room: ${conflict.room2}</small>` : ''}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
                    });
                }

                $('#conflicts-container').html(html);

                // Attach event handlers
                $('.resolve-conflict').on('click', function() {
                    const conflictId = $(this).data('id');
                    openResolveModal(conflictId);
                });
            }

            function applyFilters() {
                const type = $('#filter-type').val();
                const status = $('#filter-status').val();

                filteredConflicts = allConflicts.filter(conflict => {
                    let matchType = type === 'all' || conflict.conflict_type === type;
                    let matchStatus = status === 'all' ||
                        (status === 'resolved' && conflict.is_resolved == 1) ||
                        (status === 'unresolved' && conflict.is_resolved == 0);

                    return matchType && matchStatus;
                });

                displayConflicts(filteredConflicts);
            }

            function openResolveModal(conflictId) {
                $('#conflict-id').val(conflictId);
                $('#resolve-form')[0].reset();
                $('#resolveModal').modal('show');
            }

            function resolveConflict() {
                const formData = $('#resolve-form').serialize();

                $.ajax({
                    url: 'resolve-conflict.php',
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            $('#resolveModal').modal('hide');
                            scanForConflicts(); // Refresh conflicts
                            alert('Conflict marked as resolved');
                        } else {
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('Error resolving conflict');
                    }
                });
            }
        </script>

    </body>
    </html>
    <?php

} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>