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

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

$message = '';
$error = '';
$selectedUser = null;

$employees = getAllEmployees();

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

// Handle user update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_user'])) {
    $userId = $_POST['user_id'];
    $users = readJson('users');
    $newPassword = $_POST['new_password'];
    
    if (!empty($newPassword) && $newPassword !== strtolower($newPassword)) {
        $error = "❌ Password must be in lowercase only! No uppercase letters allowed.";
    } else {
        foreach ($users as &$user) {
            if ($user['id'] == $userId) {
                $user['email'] = $_POST['email'];
                $user['phone'] = $_POST['phone'];
                $user['full_name'] = $_POST['full_name'];
                $user['cycle'] = $_POST['cycle'];
                $user['ame_license'] = $_POST['ame_license'];
                $user['ame_expiry'] = $_POST['ame_expiry'];
                $user['raic_number'] = $_POST['raic_number'];
                $user['raic_expiry'] = $_POST['raic_expiry'];
                $user['da_number'] = $_POST['da_number'];
                $user['da_expiry'] = $_POST['da_expiry'];
                $user['amo_stamp_number'] = $_POST['amo_stamp_number'];
                $user['amo_stamp_expiry'] = $_POST['amo_stamp_expiry'];
                $user['is_active'] = isset($_POST['is_active']) ? true : false;
                
                if (!empty($newPassword)) {
                    $user['password'] = $newPassword;
                }
                
                writeJson('users', $users);
                $message = "✅ User information updated successfully!";
                $selectedUser = $user;
                break;
            }
        }
    }
}

// Handle document upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_documents'])) {
    $userId = $_POST['user_id'];
    $docType = $_POST['doc_type'];
    $uploadedCount = 0;
    $failedCount = 0;
    
    if (isset($_FILES['documents']) && !empty($_FILES['documents']['name'][0])) {
        $files = $_FILES['documents'];
        $totalFiles = count($files['name']);
        
        for ($i = 0; $i < $totalFiles; $i++) {
            if ($files['error'][$i] == 0) {
                $allowed = ['application/pdf', 'image/jpeg', 'image/png', 'image/jpg'];
                if (in_array($files['type'][$i], $allowed)) {
                    $singleFile = [
                        'name' => $files['name'][$i],
                        'tmp_name' => $files['tmp_name'][$i],
                        'type' => $files['type'][$i],
                        'error' => $files['error'][$i],
                        'size' => $files['size'][$i]
                    ];
                    if (saveUserDocument($userId, $singleFile, $docType)) {
                        $uploadedCount++;
                    } else {
                        $failedCount++;
                    }
                } else {
                    $failedCount++;
                }
            } else {
                $failedCount++;
            }
        }
        
        if ($uploadedCount > 0) {
            $message = "✅ $uploadedCount document(s) uploaded successfully.";
            if ($failedCount > 0) $message .= " ($failedCount failed)";
        } else {
            $error = "❌ No files were uploaded. Check file types (PDF, JPEG, PNG) and size.";
        }
    } else {
        $error = "❌ Please select at least one file.";
    }
    $selectedUser = getUserById($userId);
}

// Handle document deletion
if (isset($_GET['delete_doc']) && isset($_GET['user_id'])) {
    $userId = $_GET['user_id'];
    $filename = $_GET['delete_doc'];
    if (deleteUserDocument($userId, $filename)) {
        $message = "✅ Document deleted successfully!";
    } else {
        $error = "❌ Failed to delete document.";
    }
    $selectedUser = getUserById($userId);
}

// Handle user deletion
if (isset($_GET['delete_user'])) {
    $userId = $_GET['delete_user'];
    if (isset($_GET['confirm']) && $_GET['confirm'] == 'yes') {
        $users = readJson('users');
        $newUsers = [];
        foreach ($users as $user) {
            if ($user['id'] != $userId) {
                $newUsers[] = $user;
            }
        }
        writeJson('users', $newUsers);
        renumberUserIds();
        $message = "✅ User has been deleted and IDs renumbered!";
        $selectedUser = null;
        header("Location: edit_user.php?deleted=1");
        exit();
    } else {
        $confirmDelete = true;
        $deleteUserId = $userId;
    }
}

$userDocuments = [];
if ($selectedUser) {
    $userDocuments = getUserDocuments($selectedUser['id']);
}
?>
<?php include('../includes/header.php'); ?>
<style>
    .form-section {
        background: #fefcf8;
        border-radius: 20px;
        padding: 20px;
        margin-bottom: 24px;
        border: 1px solid #e2cfb3;
    }
    .form-section h3 {
        color: #6b1d2f;
        border-left: 4px solid #c9a87c;
        padding-left: 12px;
        margin-bottom: 20px;
        font-family: 'Georgia', serif;
    }
    .form-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 16px;
    }
    @media (min-width: 768px) {
        .form-grid {
            grid-template-columns: 1fr 1fr;
        }
    }
    .doc-list {
        margin-top: 15px;
    }
    .doc-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 12px;
        background: #f8efe5;
        border-radius: 12px;
        margin-bottom: 8px;
    }
    .doc-item a {
        color: #6b1d2f;
        text-decoration: none;
    }
    .delete-doc {
        color: #e74c3c;
        font-size: 0.8rem;
    }
    .employee-card {
        border: 1px solid #ddd;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 15px;
        cursor: pointer;
        transition: all 0.3s;
    }
    .employee-card:hover {
        background: #f8f9fa;
        border-color: #667eea;
    }
    .employee-card.selected {
        background: #e8f4f8;
        border-color: #667eea;
        border-width: 2px;
    }
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: bold;
    }
    .status-active {
        background: #d4edda;
        color: #155724;
    }
    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }
    .upload-note {
        font-size: 0.8rem;
        color: #8b7355;
        margin-top: 5px;
    }
</style>
<div class="sidebar">
    <h3>📋 Admin Console</h3>
    <a href="dashboard.php" class="btn">📊 Dashboard</a>
    <a href="add_user.php" class="btn">👤 Add Crew</a>
    <a href="manage_users.php" class="btn">📋 Crew List</a>
    <a href="employee_list.php" class="btn">📋 Full Employee Data</a>
    <a href="employee_chart.php" class="btn">📊 Employee Chart</a>
    <a href="edit_user.php" class="btn active">✏️ Edit Crew</a>
    <a href="manage_endorsements.php" class="btn">✈️ Endorsements</a>
    <a href="add_memo.php" class="btn">📝 New Memo</a>
    <a href="add_quiz.php" class="btn">📚 New Quiz</a>
    <a href="inbox.php" class="btn">📥 Safety Reports</a>
    <a href="chat.php" class="btn">💬 Group Chat</a>
    <a href="tools.php" class="btn">🔧 Tools Management</a>
    <a href="upload_manual.php" class="btn">📘 Upload Manual</a>
</div>
<div class="content">
    <h2>✏️ Edit Employee Information & Documents</h2>
    <p>Select an employee to edit their personal information, upload certificates/resume, or manage documents.</p>
    
    <?php if($message): ?>
        <div class="alert alert-success"><?php echo $message; ?></div>
    <?php endif; ?>
    <?php if($error): ?>
        <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    <?php if(isset($_GET['deleted'])): ?>
        <div class="alert alert-success">✅ User has been deleted successfully!</div>
    <?php endif; ?>
    
    <!-- Employee Selection -->
    <div class="card" style="margin-bottom: 20px;">
        <h3>Select Employee to Edit</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 15px;">
            <?php foreach($employees as $emp): 
                $isSelected = ($selectedUser && $selectedUser['id'] == $emp['id']);
                $isActive = isset($emp['is_active']) ? $emp['is_active'] : true;
            ?>
                <div class="employee-card <?php echo $isSelected ? 'selected' : ''; ?>" onclick="window.location.href='?user_id=<?php echo $emp['id']; ?>'">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <strong><?php echo htmlspecialchars($emp['full_name']); ?></strong>
                        <span class="status-badge <?php echo $isActive ? 'status-active' : 'status-inactive'; ?>">
                            <?php echo $isActive ? 'ACTIVE' : 'INACTIVE'; ?>
                        </span>
                    </div>
                    <small><?php echo htmlspecialchars($emp['email']); ?></small><br>
                    <small>📱 <?php echo htmlspecialchars($emp['phone']); ?></small>
                    <small><br>🔑 Username: <?php echo htmlspecialchars($emp['username']); ?></small>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <?php if($selectedUser): 
        $isActive = isset($selectedUser['is_active']) ? $selectedUser['is_active'] : true;
    ?>
        <!-- Personal Information Edit Form -->
        <div class="card">
            <h3>Editing: <?php echo htmlspecialchars($selectedUser['full_name']); ?></h3>
            <form method="POST">
                <input type="hidden" name="user_id" value="<?php echo $selectedUser['id']; ?>">
                <div class="form-section">
                    <h3>👤 Personal Information</h3>
                    <div class="form-grid">
                        <div><label>Full Name *</label><input type="text" name="full_name" value="<?php echo htmlspecialchars($selectedUser['full_name']); ?>" required></div>
                        <div><label>Username (cannot change)</label><input type="text" value="<?php echo htmlspecialchars($selectedUser['username']); ?>" disabled style="background:#f0f0f0;"></div>
                        <div><label>Email *</label><input type="email" name="email" value="<?php echo htmlspecialchars($selectedUser['email']); ?>" required></div>
                        <div><label>Phone *</label><input type="text" name="phone" value="<?php echo htmlspecialchars($selectedUser['phone']); ?>" required></div>
                        <div><label>Work Cycle</label>
                            <select name="cycle" required>
                                <option value="Even" <?php echo ($selectedUser['cycle'] ?? getUserCycle($selectedUser['id'])) == 'Even' ? 'selected' : ''; ?>>Even Cycle</option>
                                <option value="Odd" <?php echo ($selectedUser['cycle'] ?? getUserCycle($selectedUser['id'])) == 'Odd' ? 'selected' : ''; ?>>Odd Cycle</option>
                            </select>
                        </div>
                        <div><label>New Password (lowercase only)</label><input type="password" name="new_password" id="new_password" placeholder="Leave blank to keep current"></div>
                        <div><label>Status</label><label style="display:flex; align-items:center; gap:10px;"><input type="checkbox" name="is_active" value="1" <?php echo $isActive ? 'checked' : ''; ?>> Active Account</label></div>
                    </div>
                </div>
                <div class="form-section"><h3>✈️ Aviation Credentials</h3>
                    <div class="form-grid">
                        <div><label>AME License</label><input type="text" name="ame_license" value="<?php echo htmlspecialchars($selectedUser['ame_license'] ?? ''); ?>"><label>AME Expiry</label><input type="date" name="ame_expiry" value="<?php echo htmlspecialchars($selectedUser['ame_expiry'] ?? ''); ?>"></div>
                        <div><label>RAIC Number</label><input type="text" name="raic_number" value="<?php echo htmlspecialchars($selectedUser['raic_number'] ?? ''); ?>"><label>RAIC Expiry</label><input type="date" name="raic_expiry" value="<?php echo htmlspecialchars($selectedUser['raic_expiry'] ?? ''); ?>"></div>
                        <div><label>DA Number</label><input type="text" name="da_number" value="<?php echo htmlspecialchars($selectedUser['da_number'] ?? ''); ?>"><label>DA Expiry</label><input type="date" name="da_expiry" value="<?php echo htmlspecialchars($selectedUser['da_expiry'] ?? ''); ?>"></div>
                        <div><label>AMO Stamp Number</label><input type="text" name="amo_stamp_number" value="<?php echo htmlspecialchars($selectedUser['amo_stamp_number'] ?? ''); ?>"><label>AMO Stamp Expiry</label><input type="date" name="amo_stamp_expiry" value="<?php echo htmlspecialchars($selectedUser['amo_stamp_expiry'] ?? ''); ?>"></div>
                    </div>
                </div>
                <div style="display:flex; gap:10px; margin-top:20px;">
                    <button type="submit" name="update_user" class="btn btn-primary">💾 Save Changes</button>
                    <button type="button" class="delete-btn" onclick="confirmDelete(<?php echo $selectedUser['id']; ?>, '<?php echo htmlspecialchars($selectedUser['full_name']); ?>')">🗑️ Delete User</button>
                </div>
            </form>
        </div>
        
        <!-- Document Management Section -->
        <div class="card">
            <h3>📄 Documents (Resume & Certificates)</h3>
            
            <form method="POST" enctype="multipart/form-data" style="margin-bottom: 20px;">
                <input type="hidden" name="user_id" value="<?php echo $selectedUser['id']; ?>">
                <div style="display: flex; gap: 10px; flex-wrap: wrap; align-items: flex-end;">
                    <div>
                        <label>Document Type</label>
                        <select name="doc_type" required>
                            <option value="resume">📄 Resume / CV</option>
                            <option value="certificate">📜 Certificate / License</option>
                        </select>
                    </div>
                    <div>
                        <label>Select Files (up to 8)</label>
                        <input type="file" name="documents[]" multiple accept=".pdf,.jpg,.jpeg,.png" required>
                        <div class="upload-note">Allowed: PDF, JPEG, PNG (max 5MB each). You can select up to 8 files.</div>
                    </div>
                    <div>
                        <button type="submit" name="upload_documents" class="btn btn-primary">📤 Upload All</button>
                    </div>
                </div>
            </form>
            
            <h4>Existing Documents</h4>
            <?php if(empty($userDocuments)): ?>
                <p>No documents uploaded yet.</p>
            <?php else: ?>
                <div class="doc-list">
                    <?php foreach($userDocuments as $doc): ?>
                        <div class="doc-item">
                            <div>
                                <a href="<?php echo $doc['path']; ?>" target="_blank">
                                    <?php echo $doc['type'] == 'resume' ? '📄 Resume' : '📜 Certificate'; ?> 
                                    (<?php echo round($doc['size'] / 1024, 1); ?> KB)
                                </a>
                                <small> – uploaded <?php echo date('M j, Y', strtotime($doc['uploaded_at'])); ?></small>
                            </div>
                            <a href="?user_id=<?php echo $selectedUser['id']; ?>&delete_doc=<?php echo urlencode($doc['filename']); ?>" class="delete-doc" onclick="return confirm('Delete this document?')">🗑️ Delete</a>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

<script>
function confirmDelete(userId, userName) {
    if (confirm('⚠️ WARNING: Are you sure you want to delete ' + userName + '?\n\nThis action cannot be undone!\n\nAll documents and data will be permanently removed.')) {
        window.location.href = '?delete_user=' + userId + '&confirm=yes';
    }
}
var passwordField = document.getElementById('new_password');
if (passwordField) {
    passwordField.addEventListener('input', function() {
        this.value = this.value.toLowerCase().replace(/[^a-z0-9_]/g, '');
    });
}
var fileInput = document.querySelector('input[name="documents[]"]');
if (fileInput) {
    fileInput.addEventListener('change', function() {
        if (this.files.length > 8) {
            alert('You can only upload up to 8 files at once.');
            this.value = '';
        }
    });
}
</script>
<div class="clearfix"></div>
<?php include('../includes/footer.php'); ?>