<?php
/**
 * Staff Management Page
 * SSCI Office Platform - Complete Staff Directory
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('staff') . ' - ' . config('app.name');

if (!$auth->isAuthenticated() || !$auth->hasPermission('manage_staff')) {
    header('Location: ?page=login');
    exit();
}

require_once __DIR__ . '/../../layouts/header.php';

// Add responsive CSS for mobile card view
echo '<style>
@media (max-width: 768px) {
    table { display: block; border: none; }
    thead { display: none; }
    tbody { display: flex; flex-direction: column; gap: 20px; }
    tr { 
        display: block; 
        background: white;
        border: 1px solid #e5e7eb;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }
    tr:hover { background: #f9fafb; }
    td {
        display: flex;
        justify-content: space-between;
        padding: 10px 0 !important;
        border: none !important;
        border-bottom: 1px solid #f0f0f0;
    }
    td:before {
        content: attr(data-label);
        font-weight: bold;
        color: #6b7280;
        text-transform: capitalize;
        flex: 0 0 40%;
    }
    td:last-child { border: none; }
    td:last-child { 
        display: flex;
        flex-direction: column;
    }
    .overflow-x-auto { overflow: visible; }
}
</style>';


// Get action
$action = $_GET['action'] ?? 'list';
$staffId = $_GET['id'] ?? null;

// Handle contract view
if ($action === 'view_contract') {
    if (!isset($_GET['id'])) {
        header('Location: ?page=staff');
        exit();
    }
    
    $staff = $db->fetch(
        "SELECT s.*, u.name as employee_name, u.email, u.phone FROM staff s 
         JOIN users u ON s.user_id = u.id 
         WHERE s.id = ?", 
        [$_GET['id']]
    );
    
    if (!$staff) {
        header('Location: ?page=staff');
        exit();
    }
    
    // Parse remunerations if JSON
    if (!empty($staff['remunerations']) && is_string($staff['remunerations'])) {
        $staff['remunerations'] = json_decode($staff['remunerations'], true) ?: [];
    } else {
        $staff['remunerations'] = [];
    }
    
    // Get company settings
    $settings = $db->fetch("SELECT * FROM settings LIMIT 1") ?: [];
    
    // Prepare contract variables
    $contract_date = date('Y-m-d');
    $company_name = $settings['site_name'] ?? 'SHEPHERD SECURITY AND CONSULTANCY INTERNATIONAL';
    $company_address = $settings['company_address'] ?? 'Opposite PCSS Buea Town, P.O.Box 554, Buea';
    $company_email = $settings['company_email'] ?? 'info@ssci.cm';
    $company_phone = $settings['company_phone'] ?? 'Tel: (237) 676037526';
    
    // Include new contract template
    require SSCI_VIEWS . '/components/staff_contract.php';
    exit();
}

// Handle employee badge view
if ($action === 'view_badge') {
    if (!isset($_GET['id'])) {
        header('Location: ?page=staff');
        exit();
    }
    
    $staff = $db->fetch(
        "SELECT s.*, u.name as employee_name, u.email, u.phone FROM staff s 
         JOIN users u ON s.user_id = u.id 
         WHERE s.id = ?", 
        [$_GET['id']]
    );
    
    if (!$staff) {
        header('Location: ?page=staff');
        exit();
    }
    
    // Generate QR code
    $qr_data = "Staff-{$staff['staff_id']}-{$staff['employee_name']}";
    $qr_url = 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($qr_data);
    
    // Include badge template
    require SSCI_VIEWS . '/components/staff_badge.php';
    exit();
}

// Fetch all staff with user info
try {
    $staffList = $db->fetchAll(
        "SELECT s.*, u.name as employee_name, u.email 
         FROM staff s 
         JOIN users u ON s.user_id = u.id 
         ORDER BY s.position, s.zone, s.created_at DESC"
    );
} catch (Exception $e) {
    $staffList = [];
}

// Get edit data if needed
$staff = null;
if ($action === 'edit' && $staffId) {
    try {
        $staff = $db->fetch(
            "SELECT s.*, u.name as employee_name, u.email, u.phone FROM staff s 
             JOIN users u ON s.user_id = u.id 
             WHERE s.id = ?", 
            [$staffId]
        );
        if ($staff && !empty($staff['remunerations'])) {
            $staff['remunerations'] = json_decode($staff['remunerations'], true);
        }
    } catch (Exception $e) {
        $staff = null;
    }
}

// Get available users (not already staff, and not clients)
$availableUsers = [];
if ($action === 'create') {
    try {
        $availableUsers = $db->fetchAll(
            "SELECT u.id, u.name, u.email, u.role 
             FROM users u 
             WHERE u.role != 'client' 
             AND u.id NOT IN (SELECT user_id FROM staff WHERE user_id IS NOT NULL)
             ORDER BY u.name"
        );
    } catch (Exception $e) {
        $availableUsers = [];
    }
}

// Define position options in hierarchy order
$positions = ['Guard', 'Controller', 'Manager', 'Accountant', 'Marketer', 'CEO', 'VCEO', 'Other Staff'];
$zones = ['Buea', 'Limbe', 'Douala', 'Tiko', 'Yaounde', 'Bamenda', 'Kumba'];
$statuses = ['Probation', 'Volunteer', 'Permanent', 'Inactive'];
?>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-7xl pb-20 md:pb-8">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
        <div>
            <h1 class="text-4xl font-bold text-gray-800">
                <i class="fas fa-users text-blue-600 mr-3"></i>Staff Management
            </h1>
            <p class="text-gray-600 text-sm mt-2">Manage staff members, track employment details, and maintain personnel records</p>
        </div>
        <?php if ($action === 'list'): ?>
            <a href="?page=staff&action=create" class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-6 py-3 rounded-lg hover:from-blue-700 hover:to-blue-800 transition font-semibold flex items-center gap-2 shadow-lg whitespace-nowrap">
                <i class="fas fa-plus-circle"></i>Add Staff Member
            </a>
        <?php else: ?>
            <a href="?page=staff" class="text-blue-600 hover:text-blue-800 font-semibold"><i class="fas fa-arrow-left mr-2"></i>Back to Staff</a>
        <?php endif; ?>
    </div>

    <!-- Create/Edit Form -->
    <?php if ($action === 'create' || $action === 'edit'): ?>
    <div class="bg-white rounded-lg shadow-xl p-8 mb-8 border-t-4 border-blue-600">
        <div class="flex items-center gap-3 mb-6">
            <div class="w-12 h-12 rounded-full bg-blue-100 flex items-center justify-center">
                <i class="fas fa-user-tie text-blue-600 text-lg"></i>
            </div>
            <div>
                <h2 class="text-3xl font-bold text-gray-800">
                    <?php echo $action === 'create' ? 'Add New Staff Member' : 'Edit Staff Member'; ?>
                </h2>
                <p class="text-gray-600 text-sm mt-1"><?php echo $action === 'create' ? 'Create a new employee record with complete details' : 'Update employee information and employment details'; ?></p>
            </div>
        </div>

        <form id="staffForm" onsubmit="handleStaffSubmit(event, <?php echo $action === 'edit' && $staff ? $staff['id'] : 'null'; ?>)" class="space-y-6">
            
            <!-- User Selection / Info -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <?php if ($action === 'create'): ?>
                <div class="md:col-span-2">
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-user-circle text-blue-600 mr-2"></i>Employee (User Account)
                    </label>
                    <select name="user_id" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white">
                        <option value="">-- Select Employee --</option>
                        <?php foreach ($availableUsers as $user): ?>
                            <option value="<?php echo $user['id']; ?>">
                                <?php echo htmlspecialchars($user['name']); ?> (<?php echo htmlspecialchars($user['role']); ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php else: ?>
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-user-circle text-blue-600 mr-2"></i>Employee Name
                    </label>
                    <input type="text" value="<?php echo htmlspecialchars($staff['employee_name'] ?? ''); ?>" disabled class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-700">
                </div>
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-envelope text-blue-600 mr-2"></i>Email
                    </label>
                    <input type="email" value="<?php echo htmlspecialchars($staff['email'] ?? ''); ?>" disabled class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-700">
                </div>
                <?php endif; ?>

                <!-- Staff ID -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-id-badge text-blue-600 mr-2"></i>Staff ID <span class="text-red-500">*</span>
                    </label>
                    <input type="text" name="staff_id" placeholder="e.g., ST-001" required 
                           value="<?php echo htmlspecialchars($staff['staff_id'] ?? ''); ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                    <p class="text-xs text-gray-500 mt-1">Unique staff identifier</p>
                </div>

                <!-- Position -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-briefcase text-blue-600 mr-2"></i>Position <span class="text-red-500">*</span>
                    </label>
                    <select name="position" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white">
                        <?php foreach ($positions as $pos): ?>
                            <option value="<?php echo $pos; ?>" <?php echo ($staff['position'] ?? '') === $pos ? 'selected' : ''; ?>>
                                <?php echo $pos; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Zone -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-map-marker-alt text-blue-600 mr-2"></i>Zone/Location
                    </label>
                    <select name="zone" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white">
                        <option value="">-- Select Zone --</option>
                        <?php foreach ($zones as $zone): ?>
                            <option value="<?php echo $zone; ?>" <?php echo ($staff['zone'] ?? '') === $zone ? 'selected' : ''; ?>>
                                <?php echo $zone; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Status -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-toggle-on text-blue-600 mr-2"></i>Employment Status <span class="text-red-500">*</span>
                    </label>
                    <select name="status" required class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent bg-white">
                        <?php foreach ($statuses as $stat): ?>
                            <option value="<?php echo $stat; ?>" <?php echo ($staff['status'] ?? 'Probation') === $stat ? 'selected' : ''; ?>>
                                <?php echo $stat; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Contract Date -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-calendar-check text-blue-600 mr-2"></i>Contract Start Date
                    </label>
                    <input type="date" name="contract_date" 
                           value="<?php echo htmlspecialchars($staff['contract_date'] ?? date('Y-m-d')); ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>

                <!-- Contract End Date -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-calendar-times text-blue-600 mr-2"></i>Contract End Date
                    </label>
                    <input type="date" name="contract_end" 
                           value="<?php echo htmlspecialchars($staff['contract_end'] ?? ''); ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
            </div>

            <!-- Remunerations Section -->
            <div class="border-t pt-6 mt-6">
                <div class="flex items-center gap-3 mb-4">
                    <div class="w-8 h-8 rounded-full bg-green-100 flex items-center justify-center">
                        <i class="fas fa-money-bill-wave text-green-600"></i>
                    </div>
                    <h3 class="text-lg font-bold text-gray-800">Salary & Remunerations</h3>
                </div>
                <div class="overflow-x-auto mb-4">
                    <table class="w-full border border-gray-300">
                        <thead class="bg-blue-50">
                            <tr>
                                <th class="px-4 py-2 text-left font-semibold">Item</th>
                                <th class="px-4 py-2 text-right font-semibold">Amount</th>
                                <th class="px-4 py-2 text-center font-semibold">Action</th>
                            </tr>
                        </thead>
                        <tbody id="remunerationsTableBody">
                            <?php if ($action === 'edit' && !empty($staff['remunerations'])): ?>
                                <?php foreach ($staff['remunerations'] as $rem): ?>
                                <tr>
                                    <td class="border-t border-gray-300 px-4 py-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded rem-item" placeholder="e.g., Basic Salary" value="<?php echo htmlspecialchars($rem['item'] ?? ''); ?>"></td>
                                    <td class="border-t border-gray-300 px-4 py-2"><input type="number" class="w-full px-2 py-1 border border-gray-300 rounded text-right rem-amount" placeholder="0" step="0.01" value="<?php echo htmlspecialchars($rem['amount'] ?? 0); ?>" oninput="updateMonthlyTotal()"></td>
                                    <td class="border-t border-gray-300 px-4 py-2 text-center"><button type="button" onclick="removeRemunerationRow(this)" class="text-red-600 hover:text-red-800 font-bold">×</button></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <button type="button" onclick="addRemunerationRow()" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
                    <i class="fas fa-plus mr-2"></i>Add Remuneration Item
                </button>

                <!-- Total Monthly Pay -->
                <div class="mt-6 p-6 bg-gradient-to-r from-green-50 to-emerald-50 rounded-lg border-2 border-green-200 shadow-md">
                    <div class="text-sm font-semibold text-green-700 uppercase tracking-wide">Total Monthly Compensation</div>
                    <div class="text-4xl font-bold text-green-600 mt-2" id="monthlyTotalDisplay">
                        <?php echo number_format($staff['total_monthly_pay'] ?? 0, 2); ?> <span class="text-lg">FCFA</span>
                    </div>
                    <input type="hidden" name="total_monthly_pay" id="monthlyTotalInput" value="<?php echo htmlspecialchars($staff['total_monthly_pay'] ?? 0); ?>">
                </div>
            </div>

            <!-- Notes -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-sticky-note text-blue-600 mr-2"></i>Additional Notes
                </label>
                <textarea name="notes" rows="4" placeholder="Additional notes, special skills, or important information..." class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none"><?php echo htmlspecialchars($staff['notes'] ?? ''); ?></textarea>
                <p class="text-xs text-gray-500 mt-1">Optional - Add any additional information about this employee</p>
            </div>

            <!-- Submit Buttons -->
            <div class="flex gap-4 pt-6 border-t">
                <button type="submit" class="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 text-white px-8 py-4 rounded-lg hover:from-blue-700 hover:to-blue-800 transition font-semibold flex items-center justify-center gap-2 shadow-lg">
                    <i class="fas fa-check-circle"></i><?php echo $action === 'create' ? 'Create Staff Member' : 'Save Changes'; ?>
                </button>
                <a href="?page=staff" class="bg-gray-400 text-white px-8 py-4 rounded-lg hover:bg-gray-500 transition font-semibold flex items-center justify-center gap-2 shadow">
                    <i class="fas fa-times-circle"></i>Cancel
                </a>
            </div>
        </form>
    </div>

    <?php else: ?>

    <!-- Staff List -->
    <div class="grid grid-cols-1 gap-6">
        <?php if (empty($staffList)): ?>
            <div class="bg-white rounded-lg shadow-lg p-12 text-center">
                <div class="mb-4">
                    <i class="fas fa-users text-gray-300 text-6xl"></i>
                </div>
                <p class="text-gray-700 text-lg font-semibold mb-2">No Staff Members Yet</p>
                <p class="text-gray-500 mb-6">Start building your team by adding staff members</p>
                <a href="?page=staff&action=create" class="inline-block bg-blue-600 text-white px-8 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-plus-circle mr-2"></i>Add First Staff Member
                </a>
            </div>
        <?php else: ?>
            <!-- Table View -->
            <div class="bg-white rounded-lg shadow-xl overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gradient-to-r from-blue-50 to-blue-100 border-b-2 border-blue-200">
                            <tr>
                                <th class="px-6 py-4 text-left font-bold text-gray-800">Employee</th>
                                <th class="px-6 py-4 text-left font-bold text-gray-800">Staff ID</th>
                                <th class="px-6 py-4 text-left font-bold text-gray-800">Position</th>
                                <th class="px-6 py-4 text-left font-bold text-gray-800">Zone</th>
                                <th class="px-6 py-4 text-right font-bold text-gray-800">Monthly Pay</th>
                                <th class="px-6 py-4 text-left font-bold text-gray-800">Status</th>
                                <th class="px-6 py-4 text-center font-bold text-gray-800">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($staffList as $member): ?>
                            <tr class="hover:bg-blue-50 transition-colors">
                                <td class="px-6 py-4 font-semibold text-gray-800" data-label="Employee"><?php echo htmlspecialchars($member['employee_name']); ?></td>
                                <td class="px-6 py-4" data-label="Staff ID"><span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm font-semibold"><?php echo htmlspecialchars($member['staff_id']); ?></span></td>
                                <td class="px-6 py-4" data-label="Position">
                                    <span class="bg-purple-100 text-purple-800 px-3 py-1 rounded-full text-sm font-semibold"><?php echo htmlspecialchars($member['position']); ?></span>
                                </td>
                                <td class="px-6 py-4 text-gray-700" data-label="Zone"><?php echo htmlspecialchars($member['zone'] ?? '-'); ?></td>
                                <td class="px-6 py-4 text-right font-bold text-green-600" data-label="Monthly Pay"><?php echo number_format((float)($member['total_monthly_pay'] ?? 0), 2); ?> FCFA</td>
                                <td class="px-6 py-4" data-label="Status">
                                    <?php 
                                    $statusColors = [
                                        'Probation' => 'yellow',
                                        'Volunteer' => 'blue',
                                        'Permanent' => 'green',
                                        'Inactive' => 'red'
                                    ];
                                    $color = $statusColors[$member['status']] ?? 'gray';
                                    $statusIcons = [
                                        'Probation' => 'hourglass-start',
                                        'Volunteer' => 'hands-helping',
                                        'Permanent' => 'check-double',
                                        'Inactive' => 'ban'
                                    ];
                                    $icon = $statusIcons[$member['status']] ?? 'info-circle';
                                    ?>
                                    <span class="bg-<?php echo $color; ?>-100 text-<?php echo $color; ?>-800 px-3 py-1 rounded-full text-sm font-semibold flex items-center gap-1 w-fit">
                                        <i class="fas fa-<?php echo $icon; ?> text-xs"></i><?php echo htmlspecialchars($member['status']); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-center" data-label="Actions">
                                    <div class="flex gap-2 justify-center flex-wrap">
                                        <a href="?page=staff&action=view_badge&id=<?php echo $member['id']; ?>" class="text-blue-600 hover:text-blue-900 hover:bg-blue-100 p-2 rounded transition" title="View Badge">
                                            <i class="fas fa-id-card text-lg"></i>
                                        </a>
                                        <a href="?page=staff&action=view_contract&id=<?php echo $member['id']; ?>" class="text-green-600 hover:text-green-900 hover:bg-green-100 p-2 rounded transition" title="View Contract" target="_blank">
                                            <i class="fas fa-file-contract text-lg"></i>
                                        </a>
                                        <button onclick="printContract(<?php echo $member['id']; ?>)" class="text-green-600 hover:text-green-900 hover:bg-green-100 p-2 rounded transition" title="Print Contract">
                                            <i class="fas fa-print text-lg"></i>
                                        </button>
                                        <a href="?page=staff&action=edit&id=<?php echo $member['id']; ?>" class="text-orange-600 hover:text-orange-900 hover:bg-orange-100 p-2 rounded transition" title="Edit">
                                            <i class="fas fa-edit text-lg"></i>
                                        </a>
                                        <button onclick="deleteStaff(<?php echo $member['id']; ?>)" class="text-red-600 hover:text-red-900 hover:bg-red-100 p-2 rounded transition" title="Delete">
                                            <i class="fas fa-trash-alt text-lg"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <?php endif; ?>
</div>

<script>
    // API Base URL
    const API_BASE_URL = '/ssci/public/api.php';

    /**
     * Add remuneration row
     */
    function addRemunerationRow() {
        const tbody = document.getElementById('remunerationsTableBody');
        const row = document.createElement('tr');
        row.innerHTML = `
            <td class="border-t border-gray-300 px-4 py-2"><input type="text" class="w-full px-2 py-1 border border-gray-300 rounded rem-item" placeholder="e.g., Bonus"></td>
            <td class="border-t border-gray-300 px-4 py-2"><input type="number" class="w-full px-2 py-1 border border-gray-300 rounded text-right rem-amount" placeholder="0" step="0.01" oninput="updateMonthlyTotal()"></td>
            <td class="border-t border-gray-300 px-4 py-2 text-center"><button type="button" onclick="removeRemunerationRow(this)" class="text-red-600 hover:text-red-800 font-bold">×</button></td>
        `;
        tbody.appendChild(row);
        updateMonthlyTotal();
    }

    /**
     * Remove remuneration row
     */
    function removeRemunerationRow(button) {
        button.closest('tr').remove();
        updateMonthlyTotal();
    }

    /**
     * Update monthly total
     */
    function updateMonthlyTotal() {
        const rows = document.querySelectorAll('#remunerationsTableBody tr');
        let total = 0;
        rows.forEach(row => {
            const amount = parseFloat(row.querySelector('.rem-amount').value) || 0;
            total += amount;
        });
        
        document.getElementById('monthlyTotalDisplay').textContent = new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(total) + ' FCFA';
        
        document.getElementById('monthlyTotalInput').value = total;
    }

    /**
     * Handle staff form submission
     */
    function handleStaffSubmit(event, staffId) {
        event.preventDefault();
        
        const formData = new FormData(event.target);
        const data = Object.fromEntries(formData);
        
        // Collect remunerations
        const remunerations = [];
        document.querySelectorAll('#remunerationsTableBody tr').forEach(row => {
            const item = row.querySelector('.rem-item').value.trim();
            const amount = parseFloat(row.querySelector('.rem-amount').value) || 0;
            if (item) {
                remunerations.push({item, amount});
            }
        });
        
        if (remunerations.length > 0) {
            data.remunerations = JSON.stringify(remunerations);
        }
        
        data.total_monthly_pay = parseFloat(document.getElementById('monthlyTotalInput').value) || 0;
        
        const url = staffId 
            ? `${API_BASE_URL}?endpoint=staff/update&id=${staffId}`
            : `${API_BASE_URL}?endpoint=staff/create`;
        
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Staff saved successfully');
                setTimeout(() => window.location.href = '?page=staff', 1500);
            } else {
                showToast('error', data.error || 'Failed to save staff');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'Error: ' + err.message);
        });
    }

    /**
     * Delete staff
     */
    function deleteStaff(id) {
        if (!confirm('Are you sure you want to delete this staff member?')) return;
        
        fetch(`${API_BASE_URL}?endpoint=staff/delete&id=${id}`, {
            method: 'POST'
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                showToast('success', 'Staff deleted successfully');
                setTimeout(() => window.location.href = '?page=staff', 1500);
            } else {
                showToast('error', data.error || 'Failed to delete staff');
            }
        })
        .catch(err => {
            console.error('Error:', err);
            showToast('error', 'Error: ' + err.message);
        });
    }

    /**
     * Print staff contract
     */
    function printContract(id) {
        const contractWindow = window.open(`?page=staff&action=view_contract&id=${id}`, '_blank', 'width=900,height=800');
        contractWindow.addEventListener('load', function() {
            setTimeout(() => contractWindow.print(), 500);
        });
    }

    /**
     * Download contract as PDF (requires additional library)
     */
    function downloadContractPDF(id) {
        const link = document.createElement('a');
        link.href = `?page=staff&action=view_contract&id=${id}`;
        link.download = `contract-${id}.pdf`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        updateMonthlyTotal();
    });
</script>

<?php require_once __DIR__ . '/../../layouts/footer.php'; ?>
