<?php
require_once('../includes/functions.php');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'admin') {
    header("Location: ../login.php");
    exit();
}

$message = '';
$error = '';
$selectedUser = null;
$aircraftTypes = getAircraftTypes();

// Get all employees
$employees = getAllEmployees();

// Handle user selection
if (isset($_GET['user_id'])) {
    $selectedUser = getUserById($_GET['user_id']);
}

// Handle endorsement update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_endorsements'])) {
    $userId = $_POST['user_id'];
    $endorsements = isset($_POST['endorsements']) ? $_POST['endorsements'] : [];
    
    if (updateEmployeeEndorsements($userId, $endorsements)) {
        $message = "✅ Endorsements updated successfully!";
        // Refresh selected user
        $selectedUser = getUserById($userId);
    } else {
        $error = "❌ Failed to update endorsements.";
    }
}

// Handle select all/none via AJAX (optional)
$aircraftList = getAircraftTypes();
?>
<?php include('../includes/header.php'); ?>
<div class="sidebar">
    <h3>📋 Admin Menu</h3>
    <a href="dashboard.php" class="btn" style="display: block;">📊 Dashboard</a>
    <a href="add_user.php" class="btn" style="display: block;">👤 Add Employee</a>
    <a href="manage_users.php" class="btn" style="display: block;">📋 Manage Users</a>
    <a href="manage_endorsements.php" class="btn" style="display: block; background: #667eea;">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn" style="display: block;">📝 Add Memo</a>
    <a href="add_quiz.php" class="btn" style="display: block;">📚 Add Quiz</a>
    <a href="inbox.php" class="btn" style="display: block;">📥 Safety Reports</a>
    <a href="upload_manual.php" class="btn" style="display: block;">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>✈️ Aircraft Endorsements Management</h2>
    
    <?php if($message): ?>
        <div class="alert alert-info" style="background: #d4edda; border-left: 4px solid #27ae60; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>
    
    <?php if($error): ?>
        <div class="alert alert-warning" style="background: #f8d7da; border-left: 4px solid #e74c3c; padding: 15px; margin-bottom: 20px; border-radius: 5px;">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>
    
    <div class="card" style="margin-bottom: 20px;">
        <h3>Select Employee</h3>
        <div class="table-responsive">
            <table style="width: 100%;">
                <thead>
                    <tr style="background: #f8f9fa;">
                        <th>Name</th>
                        <th>Email</th>
                        <th>Current Endorsements</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($employees as $emp): 
                        $endorsements = getEmployeeEndorsements($emp['id']);
                        $endorsementDisplay = !empty($endorsements) ? implode(', ', $endorsements) : 'None';
                    ?>
                    <tr>
                        <td><?php echo htmlspecialchars($emp['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($emp['email']); ?></td>
                        <td><small><?php echo $endorsementDisplay; ?></small></td>
                        <td>
                            <a href="?user_id=<?php echo $emp['id']; ?>" class="btn" style="padding: 5px 15px; background: #667eea;">
                                ✈️ Edit Endorsements
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    
    <?php if($selectedUser): 
        $currentEndorsements = getEmployeeEndorsements($selectedUser['id']);
    ?>
        <div class="card">
            <h3>Edit Endorsements for: <?php echo htmlspecialchars($selectedUser['full_name']); ?></h3>
            <p><strong>Email:</strong> <?php echo htmlspecialchars($selectedUser['email']); ?></p>
            <p><strong>Current Endorsements:</strong> 
                <?php 
                if(!empty($currentEndorsements)){
                    echo '<span style="background: #27ae60; color: white; padding: 3px 8px; border-radius: 15px; font-size: 12px;">' . implode('</span> <span style="background: #27ae60; color: white; padding: 3px 8px; border-radius: 15px; font-size: 12px;">', $currentEndorsements) . '</span>';
                } else {
                    echo '<span style="color: #999;">No endorsements yet</span>';
                }
                ?>
            </p>
            
            <form method="POST" style="margin-top: 20px;">
                <input type="hidden" name="user_id" value="<?php echo $selectedUser['id']; ?>">
                
                <label><strong>Select Aircraft Type Endorsements:</strong></label>
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; margin: 15px 0; padding: 15px; background: #f9f9f9; border-radius: 8px;">
                    <?php foreach($aircraftTypes as $name => $code): ?>
                        <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                            <input type="checkbox" name="endorsements[]" value="<?php echo $code; ?>"
                                <?php echo in_array($code, $currentEndorsements) ? 'checked' : ''; ?>>
                            <span style="font-weight: bold;"><?php echo $code; ?></span>
                            <small style="color: #666;">(<?php echo $name; ?>)</small>
                        </label>
                    <?php endforeach; ?>
                </div>
                
                <div style="margin: 15px 0;">
                    <button type="button" class="btn" onclick="selectAll()" style="background: #3498db;">Select All</button>
                    <button type="button" class="btn" onclick="selectNone()" style="background: #95a5a6;">Select None</button>
                </div>
                
                <button type="submit" name="update_endorsements" class="btn btn-success" style="background: #27ae60; padding: 12px 24px;">
                    💾 Save Endorsements
                </button>
                <a href="manage_endorsements.php" class="btn" style="background: #e74c3c;">Cancel</a>
            </form>
        </div>
        
        <script>
            function selectAll() {
                var checkboxes = document.querySelectorAll('input[name="endorsements[]"]');
                checkboxes.forEach(function(cb) {
                    cb.checked = true;
                });
            }
            
            function selectNone() {
                var checkboxes = document.querySelectorAll('input[name="endorsements[]"]');
                checkboxes.forEach(function(cb) {
                    cb.checked = false;
                });
            }
        </script>
    <?php endif; ?>
</div>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>