<?php
session_start();
ob_start();
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['email'];
$email = $_SESSION['email'];
$intake = $_SESSION['department'];

// Handle permission form submission
$permission_message = "";
if (isset($_POST['submit_permission'])) {
    $studentid = mysqli_real_escape_string($conn, $_POST['studentid']);
    $permittedby = mysqli_real_escape_string($conn, $_POST['permittedby']);
    $days = intval($_POST['days']);
    $semester = intval($_POST['semester']);
    $year = intval($_POST['year']);
    
    // Check if student exists
    $check_student = $conn->query("SELECT * FROM students WHERE studentid = '$studentid'");
    
    if ($check_student && $check_student->num_rows > 0) {
        // Check if permission already exists for this semester and year
        $check_permission = $conn->query("SELECT * FROM permit WHERE studentid = '$studentid' AND semester = '$semester' AND year = '$year'");
        
        if ($check_permission && $check_permission->num_rows > 0) {
            $permission_message = "<div class='alert alert-warning'>Permission already exists for this student in semester $semester, $year!</div>";
        } else {
            // Insert permission
            $sql = "INSERT INTO permit (studentid, permittedby, days, semester, year, created_date) 
                    VALUES ('$studentid', '$permittedby', '$days', '$semester', '$year', NOW())";
            
            if ($conn->query($sql)) {
                $permission_message = "<div class='alert alert-success'>Permission granted successfully for $days days!</div>";
            } else {
                $permission_message = "<div class='alert alert-danger'>Error: " . $conn->error . "</div>";
            }
        }
    } else {
        $permission_message = "<div class='alert alert-danger'>Student ID '$studentid' not found!</div>";
    }
}

// Handle delete permission
if (isset($_GET['delete_id'])) {
    $delete_id = intval($_GET['delete_id']);
    
    // Delete the permission
    $delete_query = "DELETE FROM permit WHERE id = $delete_id";
    if ($conn->query($delete_query)) {
        $delete_message = "<div class='alert alert-success'>Permission deleted successfully!</div>";
        // Redirect to clear the delete_id from URL
        header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
        exit();
    } else {
        $delete_message = "<div class='alert alert-danger'>Error deleting permission: " . $conn->error . "</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Permission Management</title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary) !important">
    <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<style>
    body{
        padding: 0px;
        margin:0px;
        font-size:16px;
        width:100%;
        background:white;
    }
   
    .btn{
        background:var(--primary) !important;
        border:none;
        border-radius:2px;
        outline:none;
        color: white;
        margin-right:10px;
        margin-bottom:10px;
    }
    .btn:hover{
        background:gray;
    }
    .content{
        margin-left:200px;
        padding:20px;
    }
    .permission-table {
        margin-top: 20px;
    }
    .status-active {
        background-color: #d4edda;
        color: #155724;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 12px;
    }
    .status-expired {
        background-color: #f8d7da;
        color: #721c24;
        padding: 3px 8px;
        border-radius: 4px;
        font-size: 12px;
    }
    .filter-section {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 5px;
        margin-bottom: 20px;
    }
    @media (max-width: 768px) {
        .content {
            margin-left: 0;
            padding: 10px;
        }
    }
    /* Delete Modal Styles */
    .modal-content {
        border-radius: 10px;
    }
    .modal-header {
        background: var(--primary) !important;
        color: white;
        border-radius: 10px 10px 0 0;
    }
    .btn{
        color: white !important;
    }
</style>
<body>
<?php include "../include/nav.php";?>

<div class="content">
    <!-- Display delete message if exists -->
    <?php if (isset($delete_message)) echo $delete_message; ?>
    

    <!-- Permission Form Section -->
    <div class="card">
        <div class="card-header" style="background:var(--secondary); color:white;">
            <h5 class="mb-0"><i class="fa fa-key"></i> Grant Special Fee Clearance Permission</h5>
        </div>
        <div class="card-body">
            <?php echo $permission_message; ?>
            
            <form method="POST">
                <div class="row">
                    <!-- Student ID -->
                    <div class="col-md-6 mb-3">
                        <label style="font-weight:bold;">Student ID <span class="text-danger">*</span></label>
                        <input type="text" name="studentid" class="form-control" placeholder="Enter Student ID" required>
                    </div>
                    
                    <!-- Permitted By -->
                    <div class="col-md-6 mb-3">
                        <label style="font-weight:bold;">Permitted By <span class="text-danger">*</span></label>
                        <input type="text" name="permittedby" class="form-control" placeholder="Enter your name"  required>
                    </div>
                    
                    <!-- Days Valid -->
                    <div class="col-md-4 mb-3">
                        <label style="font-weight:bold;">Days Valid <span class="text-danger">*</span></label>
                        <input type="number" name="days" class="form-control" placeholder="Number of days" min="1" max="365" required>
                    </div>
                    
                    <!-- Semester -->
                    <div class="col-md-4 mb-3">
                        <label style="font-weight:bold;">Semester <span class="text-danger">*</span></label>
                        <select name="semester" class="form-control" required>
                            <option value="">-- Select --</option>
                            <option value="1">Semester 1</option>
                            <option value="2">Semester 2</option>
                        </select>
                    </div>
                    
                    <!-- Year -->
                    <div class="col-md-4 mb-3">
                        <label style="font-weight:bold;">Year <span class="text-danger">*</span></label>
                        <select name="year" class="form-control" required>
                            <option value="">-- Select --</option>
                            <?php 
                            $current_year = date('Y');
                            for($i = $current_year - 2; $i <= $current_year + 2; $i++) {
                                $selected = ($i == $current_year) ? 'selected' : '';
                                echo "<option value='$i' $selected>$i</option>";
                            }
                            ?>
                        </select>
                    </div>
                </div>
                
                <!-- Submit Button -->
                <div style="text-align:left; margin-top:20px;">
                    <button type="submit" name="submit_permission" class="btn" style="background:;">
                        <i class="fa fa-save"></i> Grant Permission
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Filter Section -->
    <div class="card mt-4">
        <div class="card-header" style="background:var(--secondary); color:white;">
            <h5 class="mb-0"><i class="fa fa-filter"></i> Filter Permissions</h5>
        </div>
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-3">
                    <label style="font-weight:bold;">Student ID</label>
                    <input type="text" name="studentid" class="form-control" placeholder="Enter Student ID" value="<?php echo $_GET['studentid'] ?? ''; ?>">
                </div>
                <div class="col-md-3">
                    <label style="font-weight:bold;">Semester</label>
                    <select name="semester" class="form-control">
                        <option value="">All Semesters</option>
                        <option value="1" <?php echo (isset($_GET['semester']) && $_GET['semester'] == '1') ? 'selected' : ''; ?>>Semester 1</option>
                        <option value="2" <?php echo (isset($_GET['semester']) && $_GET['semester'] == '2') ? 'selected' : ''; ?>>Semester 2</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label style="font-weight:bold;">Year</label>
                    <select name="year" class="form-control">
                        <option value="">All Years</option>
                        <?php 
                        $current_year = date('Y');
                        for($i = $current_year - 2; $i <= $current_year + 2; $i++) {
                            $selected = (isset($_GET['year']) && $_GET['year'] == $i) ? 'selected' : '';
                            echo "<option value='$i' $selected>$i</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label style="font-weight:bold;">Status</label>
                    <select name="status" class="form-control">
                        <option value="">All Status</option>
                        <option value="active" <?php echo (isset($_GET['status']) && $_GET['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                        <option value="expired" <?php echo (isset($_GET['status']) && $_GET['status'] == 'expired') ? 'selected' : ''; ?>>Expired</option>
                    </select>
                </div>
                <div class="col-md-12 text-right">
                    <button type="submit" class="btn btn-primary">
                        <i class="fa fa-search"></i> Apply Filter
                    </button>
                    <a href="?" class="btn btn-secondary">
                        <i class="fa fa-refresh"></i> Clear Filter
                    </a>
                </div>
            </form>
        </div>
    </div>

    <!-- List of Students with Permissions -->
    <div class="card mt-4">
        <div class="card-header" style="background:var(--secondary); color:white;">
            <h5 class="mb-0"><i class="fa fa-list"></i> Students with Special Permissions</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Student ID</th>
                            <th>Student Name</th>
                            <th>Program</th>
                            <th>Permitted By</th>
                            <th>Days</th>
                            <th>Semester</th>
                            <th>Year</th>
                            <th>Granted Date</th>
                            <th>Expiry Date</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Build filter query
                        $where_conditions = [];
                        $filter_params = [];
                        
                        if (isset($_GET['studentid']) && !empty($_GET['studentid'])) {
                            $where_conditions[] = "p.studentid LIKE ?";
                            $filter_params[] = "%" . $_GET['studentid'] . "%";
                        }
                        
                        if (isset($_GET['semester']) && !empty($_GET['semester'])) {
                            $where_conditions[] = "p.semester = ?";
                            $filter_params[] = $_GET['semester'];
                        }
                        
                        if (isset($_GET['year']) && !empty($_GET['year'])) {
                            $where_conditions[] = "p.year = ?";
                            $filter_params[] = $_GET['year'];
                        }
                        
                        // Base query
                        $permissions_query = "SELECT p.*, s.studentname, s.program 
                                             FROM permit p 
                                             LEFT JOIN students s ON p.studentid = s.studentid";
                        
                        // Add where conditions if any
                        if (!empty($where_conditions)) {
                            $permissions_query .= " WHERE " . implode(" AND ", $where_conditions);
                        }
                        
                        $permissions_query .= " ORDER BY p.created_date DESC";
                        
                        // Prepare and execute query
                        $stmt = $conn->prepare($permissions_query);
                        
                        if ($stmt) {
                            // Bind parameters if any
                            if (!empty($filter_params)) {
                                $types = str_repeat('s', count($filter_params));
                                $stmt->bind_param($types, ...$filter_params);
                            }
                            
                            $stmt->execute();
                            $permissions_result = $stmt->get_result();
                            
                            if ($permissions_result && $permissions_result->num_rows > 0) {
                                $counter = 1;
                                while($row = $permissions_result->fetch_assoc()) {
                                    $granted_date = date('Y-m-d', strtotime($row['created_date']));
                                    $expiry_date = date('Y-m-d', strtotime($row['created_date'] . ' + ' . $row['days'] . ' days'));
                                    $current_date = date('Y-m-d');
                                    
                                    $status = ($current_date <= $expiry_date) ? 
                                        '<span class="status-active">Active</span>' : 
                                        '<span class="status-expired">Expired</span>';
                                    
                                    // Apply status filter if set
                                    if (isset($_GET['status']) && !empty($_GET['status'])) {
                                        if ($_GET['status'] == 'active' && $current_date > $expiry_date) {
                                            continue;
                                        }
                                        if ($_GET['status'] == 'expired' && $current_date <= $expiry_date) {
                                            continue;
                                        }
                                    }
                                    
                                    echo "<tr>
                                            <td>{$counter}</td>
                                            <td>{$row['studentid']}</td>
                                            <td>{$row['studentname']}</td>
                                            <td>{$row['program']}</td>
                                            <td>{$row['permittedby']}</td>
                                            <td>{$row['days']}</td>
                                            <td>Semester {$row['semester']}</td>
                                            <td>{$row['year']}</td>
                                            <td>{$granted_date}</td>
                                            <td>{$expiry_date}</td>
                                            <td>{$status}</td>
                                            <td>
                                                <button type='button' class='btn btn-sm btn-danger' 
                                                        data-toggle='modal' data-target='#deleteModal{$row['id']}'>
                                                    <i class='fa fa-trash'></i>
                                                </button>
                                            </td>
                                          </tr>";
                                    
                                    // Generate delete modal for each row
                                    echo "
                                    <!-- Delete Modal for ID {$row['id']} -->
                                    <div class='modal fade' id='deleteModal{$row['id']}' tabindex='-1' role='dialog' aria-labelledby='deleteModalLabel{$row['id']}' aria-hidden='true'>
                                        <div class='modal-dialog' role='document'>
                                            <div class='modal-content'>
                                                <div class='modal-header'>
                                                    <h5 class='modal-title' id='deleteModalLabel{$row['id']}'>Confirm Deletion</h5>
                                                    <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                                                        <span aria-hidden='true'>&times;</span>
                                                    </button>
                                                </div>
                                                <div class='modal-body'>
                                                    <p>Are you sure you want to delete the permission for:</p>
                                                    <p><strong>Student:</strong> {$row['studentname']} ({$row['studentid']})</p>
                                                    <p><strong>Granted By:</strong> {$row['permittedby']}</p>
                                                    <p><strong>Semester:</strong> {$row['semester']}, <strong>Year:</strong> {$row['year']}</p>
                                                    <p class='text-danger'><i class='fa fa-exclamation-triangle'></i> This action cannot be undone!</p>
                                                </div>
                                                <div class='modal-footer'>
                                                    <button type='button' class='btn btn-secondary' data-dismiss='modal'>Cancel</button>
                                                    <a href='?delete_id={$row['id']}&" . http_build_query($_GET) . "' class='btn btn-danger'>Delete</a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>";
                                    $counter++;
                                }
                            } else {
                                echo "<tr><td colspan='12' class='text-center text-muted'>No permissions found matching your criteria.</td></tr>";
                            }
                            
                            $stmt->close();
                        } else {
                            echo "<tr><td colspan='12' class='text-center text-danger'>Error preparing query.</td></tr>";
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

<script>
// Live search functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[name="studentid"]');
    const tableRows = document.querySelectorAll('tbody tr');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const filter = this.value.toLowerCase();
            
            tableRows.forEach(row => {
                const studentId = row.cells[1]?.textContent?.toLowerCase() || '';
                const studentName = row.cells[2]?.textContent?.toLowerCase() || '';
                
                if (studentId.includes(filter) || studentName.includes(filter)) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });
    }
    
    // Auto-hide alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            alert.style.transition = 'opacity 0.5s';
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 500);
        });
    }, 5000);
});
</script>

</body>
</html>