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

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

$employees = getAllEmployees();
$aircraftTypes = getAircraftTypes();

// Handle AJAX save request
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    header('Content-Type: application/json');
    $userId = intval($_POST['user_id']);
    $field = $_POST['field'];
    $value = $_POST['value'];
    
    $users = readJson('users');
    $updated = false;
    
    foreach ($users as &$user) {
        if ($user['id'] == $userId) {
            if ($field == 'cycle') {
                $user['cycle'] = $value;
            } elseif ($field == 'full_name') {
                $user['full_name'] = $value;
            } elseif ($field == 'username') {
                $user['username'] = strtolower($value);
            } elseif ($field == 'email') {
                $user['email'] = $value;
            } elseif ($field == 'phone') {
                $user['phone'] = $value;
            } elseif ($field == 'raic_number') {
                $user['raic_number'] = $value;
            } elseif ($field == 'raic_expiry') {
                $user['raic_expiry'] = $value;
            } elseif ($field == 'da_number') {
                $user['da_number'] = $value;
            } elseif ($field == 'endorsements') {
                $user['endorsements'] = explode(',', $value);
            }
            $updated = true;
            break;
        }
    }
    
    if ($updated) {
        writeJson('users', $users);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false]);
    }
    exit;
}

// Sort employees: Even first, then Odd, then by name
usort($employees, function($a, $b) {
    $cycleA = getUserCycle($a['id']);
    $cycleB = getUserCycle($b['id']);
    if ($cycleA === $cycleB) {
        return strcmp($a['full_name'], $b['full_name']);
    }
    return ($cycleA === 'Even') ? -1 : 1;
});

function getExpiryStatusClass($date) {
    if (empty($date)) return '';
    $today = strtotime(date('Y-m-d'));
    $expiry = strtotime($date);
    $daysLeft = floor(($expiry - $today) / (60 * 60 * 24));
    if ($daysLeft < 0) return 'status-expired';
    if ($daysLeft <= 30) return 'status-critical';
    if ($daysLeft <= 90) return 'status-warning';
    return '';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Employee Chart - RxAero</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Arial, sans-serif;
            background: white;
            padding: 20px;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        h1 {
            font-size: 1.8rem;
            margin-bottom: 10px;
            color: #2c3e50;
            border-bottom: 2px solid #ccc;
            padding-bottom: 10px;
        }
        .subhead {
            color: #666;
            margin-bottom: 20px;
            font-size: 0.9rem;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.8rem;
        }
        th {
            background: #2c3e50;
            color: white;
            padding: 10px 8px;
            text-align: left;
            font-weight: 600;
            border: 1px solid #34495e;
        }
        td {
            padding: 8px;
            border: 1px solid #ddd;
            vertical-align: top;
        }
        tr.even-cycle {
            background-color: #dbeafe;
        }
        tr.odd-cycle {
            background-color: #fee2e2;
        }
        .status-warning {
            background-color: #fff3cd;
            color: #856404;
            font-weight: bold;
        }
        .status-critical {
            background-color: #f8d7da;
            color: #721c24;
            font-weight: bold;
        }
        .status-expired {
            background-color: #e74c3c;
            color: white;
            font-weight: bold;
        }
        .cycle-badge {
            display: inline-block;
            background: #c9a87c;
            color: #2c1e12;
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: bold;
        }
        .endorsement-badge {
            display: inline-block;
            background: #6b1d2f;
            color: white;
            padding: 2px 6px;
            border-radius: 12px;
            font-size: 0.65rem;
            margin: 2px;
        }
        .edit-btn, .save-btn, .cancel-btn {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.7rem;
            cursor: pointer;
            border: none;
            margin: 2px;
        }
        .edit-btn {
            background: #3498db;
            color: white;
        }
        .save-btn {
            background: #27ae60;
            color: white;
        }
        .cancel-btn {
            background: #95a5a6;
            color: white;
        }
        .edit-select, .edit-input {
            width: 100%;
            padding: 4px;
            font-size: 0.75rem;
            border-radius: 4px;
            border: 1px solid #ccc;
        }
        .edit-mode {
            background-color: #fff8e1 !important;
        }
        @media print {
            .edit-btn, .save-btn, .cancel-btn, .action-column {
                display: none !important;
            }
            body { padding: 0; margin: 0; }
            th { background: #2c3e50; color: white; print-color-adjust: exact; }
            tr.even-cycle { background-color: #dbeafe !important; print-color-adjust: exact; }
            tr.odd-cycle { background-color: #fee2e2 !important; print-color-adjust: exact; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
            <h1>RxAero Employee Overview</h1>
            <button onclick="window.print()" style="padding: 6px 12px; background: #2c3e50; color: white; border: none; border-radius: 4px; cursor: pointer;">🖨️ Print</button>
        </div>
        <div class="subhead">Generated: <?php echo date('F j, Y g:i A'); ?> | Total Employees: <?php echo count($employees); ?></div>
        
        <div class="table-responsive">
            <table id="employeeTable">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Cycle</th>
                        <th>RAIC #</th>
                        <th>RAIC Expiry</th>
                        <th>DA #</th>
                        <th>Aircraft Endorsements</th>
                        <th>Email / Phone</th>
                        <th class="action-column">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($employees as $emp): 
                        $cycle = getUserCycle($emp['id']);
                        $endorsements = getEmployeeEndorsements($emp['id']);
                        $raicExpiryClass = getExpiryStatusClass($emp['raic_expiry'] ?? '');
                    ?>
                        <tr id="row-<?php echo $emp['id']; ?>" class="<?php echo ($cycle == 'Even') ? 'even-cycle' : 'odd-cycle'; ?>">
                            <td class="name-cell" data-field="full_name" data-value="<?php echo htmlspecialchars($emp['full_name']); ?>">
                                <?php echo htmlspecialchars($emp['full_name']); ?>
                            </td>
                            <td class="cycle-cell" data-field="cycle" data-value="<?php echo $cycle; ?>">
                                <span class="cycle-badge"><?php echo $cycle; ?></span>
                            </td>
                            <td class="raic-cell" data-field="raic_number" data-value="<?php echo htmlspecialchars($emp['raic_number'] ?? ''); ?>">
                                <?php echo htmlspecialchars($emp['raic_number'] ?: '-'); ?>
                            </td>
                            <td class="raic-expiry-cell" data-field="raic_expiry" data-value="<?php echo $emp['raic_expiry'] ?? ''; ?>">
                                <span class="<?php echo $raicExpiryClass; ?>"><?php echo $emp['raic_expiry'] ?: '-'; ?></span>
                            </td>
                            <td class="da-cell" data-field="da_number" data-value="<?php echo htmlspecialchars($emp['da_number'] ?? ''); ?>">
                                <?php echo htmlspecialchars($emp['da_number'] ?: '-'); ?>
                            </td>
                            <td class="endorsements-cell" data-field="endorsements" data-value="<?php echo implode(',', $endorsements); ?>">
                                <?php if(!empty($endorsements)): ?>
                                    <?php foreach($endorsements as $code): ?>
                                        <span class="endorsement-badge"><?php echo $code; ?></span>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <span style="color:#999;">—</span>
                                <?php endif; ?>
                            </td>
                            <td class="contact-cell">
                                <?php echo htmlspecialchars($emp['email']); ?><br>
                                <?php echo htmlspecialchars($emp['phone']); ?>
                            </td>
                            <td class="action-column">
                                <button class="edit-btn" onclick="editRow(<?php echo $emp['id']; ?>)">✏️ Edit</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div style="margin-top: 20px; font-size: 0.7rem; color: #999; text-align: center;">
            RxAero Aviation Maintenance Portal – Employee Data Report | Click Edit to modify employee information
        </div>
    </div>

    <script>
        let currentEditRow = null;
        const aircraftTypes = <?php echo json_encode(array_values($aircraftTypes)); ?>;
        
        function editRow(userId) {
            // If already editing another row, cancel it first
            if (currentEditRow && currentEditRow !== userId) {
                cancelEdit(currentEditRow);
            }
            
            const row = document.getElementById(`row-${userId}`);
            if (!row) return;
            
            currentEditRow = userId;
            row.classList.add('edit-mode');
            
            // Get current values
            const nameCell = row.querySelector('.name-cell');
            const cycleCell = row.querySelector('.cycle-cell');
            const raicCell = row.querySelector('.raic-cell');
            const raicExpiryCell = row.querySelector('.raic-expiry-cell');
            const daCell = row.querySelector('.da-cell');
            const endorsementsCell = row.querySelector('.endorsements-cell');
            const contactCell = row.querySelector('.contact-cell');
            const actionCell = row.querySelector('.action-column');
            
            const currentName = nameCell.dataset.value;
            const currentCycle = cycleCell.dataset.value;
            const currentRaic = raicCell.dataset.value;
            const currentRaicExpiry = raicExpiryCell.dataset.value;
            const currentDa = daCell.dataset.value;
            const currentEndorsements = endorsementsCell.dataset.value ? endorsementsCell.dataset.value.split(',') : [];
            
            // Get email and phone from contact cell
            const contactHtml = contactCell.innerHTML;
            const emailMatch = contactHtml.match(/([^\s<]+@[^\s>]+)/);
            const phoneMatch = contactHtml.match(/📱\s*([\d\s\+\(\)\-]+)/);
            const currentEmail = emailMatch ? emailMatch[1] : '';
            const currentPhone = phoneMatch ? phoneMatch[1] : '';
            
            // Create edit fields
            nameCell.innerHTML = `<input type="text" class="edit-input" id="edit-name-${userId}" value="${escapeHtml(currentName)}">`;
            cycleCell.innerHTML = `<select class="edit-select" id="edit-cycle-${userId}">
                <option value="Even" ${currentCycle === 'Even' ? 'selected' : ''}>Even Cycle</option>
                <option value="Odd" ${currentCycle === 'Odd' ? 'selected' : ''}>Odd Cycle</option>
            </select>`;
            raicCell.innerHTML = `<input type="text" class="edit-input" id="edit-raic-${userId}" value="${escapeHtml(currentRaic)}">`;
            raicExpiryCell.innerHTML = `<input type="date" class="edit-input" id="edit-raic-expiry-${userId}" value="${escapeHtml(currentRaicExpiry)}">`;
            daCell.innerHTML = `<input type="text" class="edit-input" id="edit-da-${userId}" value="${escapeHtml(currentDa)}">`;
            
            // Endorsements as multi-select
            let endorsementsHtml = `<select multiple class="edit-select" id="edit-endorsements-${userId}" size="5">`;
            aircraftTypes.forEach(type => {
                endorsementsHtml += `<option value="${type}" ${currentEndorsements.includes(type) ? 'selected' : ''}>${type}</option>`;
            });
            endorsementsHtml += `</select><small style="font-size:0.6rem;">Hold Ctrl/Cmd to select multiple</small>`;
            endorsementsCell.innerHTML = endorsementsHtml;
            
            contactCell.innerHTML = `
                <input type="email" class="edit-input" id="edit-email-${userId}" value="${escapeHtml(currentEmail)}" placeholder="Email"><br>
                <input type="text" class="edit-input" id="edit-phone-${userId}" value="${escapeHtml(currentPhone)}" placeholder="Phone">
            `;
            
            actionCell.innerHTML = `
                <button class="save-btn" onclick="saveRow(${userId})">💾 Save</button>
                <button class="cancel-btn" onclick="cancelEdit(${userId})">✖️ Cancel</button>
            `;
        }
        
        function saveRow(userId) {
            const row = document.getElementById(`row-${userId}`);
            if (!row) return;
            
            // Collect all values from edit fields
            const newName = document.getElementById(`edit-name-${userId}`)?.value || '';
            const newCycle = document.getElementById(`edit-cycle-${userId}`)?.value || '';
            const newRaic = document.getElementById(`edit-raic-${userId}`)?.value || '';
            const newRaicExpiry = document.getElementById(`edit-raic-expiry-${userId}`)?.value || '';
            const newDa = document.getElementById(`edit-da-${userId}`)?.value || '';
            const newEmail = document.getElementById(`edit-email-${userId}`)?.value || '';
            const newPhone = document.getElementById(`edit-phone-${userId}`)?.value || '';
            
            const endorsementsSelect = document.getElementById(`edit-endorsements-${userId}`);
            const newEndorsements = endorsementsSelect ? Array.from(endorsementsSelect.selectedOptions).map(opt => opt.value) : [];
            
            // Save each field via AJAX
            const fields = [
                { field: 'full_name', value: newName },
                { field: 'cycle', value: newCycle },
                { field: 'raic_number', value: newRaic },
                { field: 'raic_expiry', value: newRaicExpiry },
                { field: 'da_number', value: newDa },
                { field: 'endorsements', value: newEndorsements.join(',') }
            ];
            
            let savePromises = fields.map(f => 
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: `user_id=${userId}&field=${f.field}&value=${encodeURIComponent(f.value)}`
                }).then(res => res.json())
            );
            
            // Also save email and phone via separate calls (they need to be saved directly to user)
            savePromises.push(
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: `user_id=${userId}&field=email&value=${encodeURIComponent(newEmail)}`
                }).then(res => res.json())
            );
            savePromises.push(
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: `user_id=${userId}&field=phone&value=${encodeURIComponent(newPhone)}`
                }).then(res => res.json())
            );
            
            Promise.all(savePromises).then(results => {
                if (results.every(r => r.success)) {
                    // Reload page to reflect changes
                    window.location.reload();
                } else {
                    alert('Some changes failed to save. Please try again.');
                }
            }).catch(() => {
                alert('Error saving changes.');
            });
        }
        
        function cancelEdit(userId) {
            window.location.reload();
        }
        
        function escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>]/g, function(m) {
                if (m === '&') return '&amp;';
                if (m === '<') return '&lt;';
                if (m === '>') return '&gt;';
                return m;
            });
        }
    </script>
</body>
</html>