<?php
require_once __DIR__ . '/../config/config.php';
requireLogin();

$success = '';
$error = '';

// 處理新增/編輯員工
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $name = $_POST['name'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $salary_type = $_POST['salary_type'] ?? 'daily';
    $salary_amount = $_POST['salary_amount'] ?? 0;
    $id = $_POST['id'] ?? null;

    $id_card_path = $_POST['existing_id_card'] ?? null;
    $safety_card_path = $_POST['existing_safety_card'] ?? null;

    // 處理文件上傳
    if (isset($_FILES['id_card']) && $_FILES['id_card']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['id_card']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('id_') . '.' . $ext;
        move_uploaded_file($_FILES['id_card']['tmp_name'], UPLOAD_DIR . 'id_cards/' . $filename);
        $id_card_path = 'uploads/id_cards/' . $filename;
    }

    if (isset($_FILES['safety_card']) && $_FILES['safety_card']['error'] === UPLOAD_ERR_OK) {
        $ext = pathinfo($_FILES['safety_card']['name'], PATHINFO_EXTENSION);
        $filename = uniqid('sc_') . '.' . $ext;
        move_uploaded_file($_FILES['safety_card']['tmp_name'], UPLOAD_DIR . 'safety_cards/' . $filename);
        $safety_card_path = 'uploads/safety_cards/' . $filename;
    }

    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO employees (name, id_card_path, safety_card_path, phone, salary_type, salary_amount) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$name, $id_card_path, $safety_card_path, $phone, $salary_type, $salary_amount]);
        $success = '員工已成功新增';
    } elseif ($action === 'edit' && $id) {
        $stmt = $pdo->prepare("UPDATE employees SET name = ?, id_card_path = ?, safety_card_path = ?, phone = ?, salary_type = ?, salary_amount = ? WHERE id = ?");
        $stmt->execute([$name, $id_card_path, $safety_card_path, $phone, $salary_type, $salary_amount, $id]);
        $success = '員工資料已更新';
    }
}

// 處理刪除
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM employees WHERE id = ?");
    $stmt->execute([$id]);
    $success = '員工已成功刪除';
}

// 獲取所有員工
$employees = $pdo->query("SELECT * FROM employees ORDER BY created_at DESC")->fetchAll();

include __DIR__ . '/../includes/header.php';
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h1 class="text-2xl font-bold text-slate-800">員工管理</h1>
        <p class="text-slate-500">管理公司直屬員工資料及薪酬設定</p>
    </div>
    <button onclick="openModal('add')" 
        class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center shadow-sm transition">
        <i class="fas fa-plus mr-2"></i> 新增員工
    </button>
</div>

<?php if ($success): ?>
    <div class="bg-green-50 text-green-600 p-4 rounded-lg mb-6 flex items-center">
        <i class="fas fa-check-circle mr-2"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<!-- Employee List -->
<div class="bg-white rounded-2xl shadow-sm border border-slate-100 overflow-hidden">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-100 text-slate-500 text-sm font-semibold">
                <tr>
                    <th class="px-6 py-4">姓名</th>
                    <th class="px-6 py-4">電話</th>
                    <th class="px-6 py-4">證件</th>
                    <th class="px-6 py-4">薪酬類型</th>
                    <th class="px-6 py-4">薪酬金額</th>
                    <th class="px-6 py-4 text-right">操作</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php foreach ($employees as $emp): ?>
                <tr class="hover:bg-slate-50 transition">
                    <td class="px-6 py-4 font-medium text-slate-800"><?php echo htmlspecialchars($emp['name']); ?></td>
                    <td class="px-6 py-4 text-slate-600"><?php echo htmlspecialchars($emp['phone'] ?: '-'); ?></td>
                    <td class="px-6 py-4">
                        <div class="flex gap-2">
                            <?php if ($emp['id_card_path']): ?>
                                <a href="../<?php echo $emp['id_card_path']; ?>" target="_blank" class="text-blue-500 hover:underline text-xs">身份證</a>
                            <?php endif; ?>
                            <?php if ($emp['safety_card_path']): ?>
                                <a href="../<?php echo $emp['safety_card_path']; ?>" target="_blank" class="text-green-500 hover:underline text-xs">安全卡</a>
                            <?php endif; ?>
                        </div>
                    </td>
                    <td class="px-6 py-4">
                        <span class="px-2 py-1 rounded text-xs font-semibold <?php echo $emp['salary_type'] === 'daily' ? 'bg-orange-100 text-orange-600' : 'bg-blue-100 text-blue-600'; ?>">
                            <?php echo $emp['salary_type'] === 'daily' ? '日薪' : '月薪'; ?>
                        </span>
                    </td>
                    <td class="px-6 py-4 text-slate-800 font-bold">$<?php echo format_amount($emp['salary_amount']); ?></td>
                    <td class="px-6 py-4 text-right space-x-3">
                        <button onclick='openModal("edit", <?php echo json_encode($emp); ?>)' class="text-slate-400 hover:text-blue-600 transition">
                            <i class="fas fa-edit"></i>
                        </button>
                        <a href="?delete=<?php echo $emp['id']; ?>" onclick="return confirm('確定要刪除此員工嗎？')" 
                            class="text-slate-400 hover:text-red-600 transition">
                            <i class="fas fa-trash-alt"></i>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal -->
<div id="worker-modal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-2xl w-full max-w-2xl p-8 shadow-2xl transform transition-all overflow-y-auto max-h-[90vh]">
        <div class="flex justify-between items-center mb-6">
            <h2 id="modal-title" class="text-xl font-bold text-slate-800">新增員工</h2>
            <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <form action="employees.php" method="POST" enctype="multipart/form-data" class="space-y-6">
            <input type="hidden" name="action" id="form-action" value="add">
            <input type="hidden" name="id" id="worker-id">
            <input type="hidden" name="existing_id_card" id="existing-id-card">
            <input type="hidden" name="existing_safety_card" id="existing-safety-card">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">姓名 *</label>
                    <input type="text" name="name" id="worker-name" required 
                        class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">電話號碼</label>
                    <input type="text" name="phone" id="worker-phone"
                        class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">薪酬類型</label>
                    <select name="salary_type" id="worker-salary-type" class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                        <option value="daily">日薪</option>
                        <option value="monthly">月薪</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">薪酬金額</label>
                    <input type="number" step="0.01" name="salary_amount" id="worker-salary-amount"
                        class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-blue-500 outline-none">
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">身份證 (上傳圖片)</label>
                    <input type="file" name="id_card" accept="image/*"
                        class="w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                    <p id="id-card-status" class="mt-1 text-xs text-blue-500 hidden italic">已有文件上傳</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-slate-700 mb-1">安全卡 (上傳圖片)</label>
                    <input type="file" name="safety_card" accept="image/*"
                        class="w-full text-sm text-slate-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-green-50 file:text-green-700 hover:file:bg-green-100">
                    <p id="safety-card-status" class="mt-1 text-xs text-green-500 hidden italic">已有文件上傳</p>
                </div>
            </div>

            <div class="pt-4 flex gap-3 border-t border-slate-100">
                <button type="button" onclick="closeModal()" 
                    class="flex-1 px-4 py-3 border border-slate-200 text-slate-600 rounded-lg hover:bg-slate-50 transition">
                    取消
                </button>
                <button type="submit" class="flex-1 px-4 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 shadow-lg transition">
                    確認保存
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    function openModal(mode, data = null) {
        const modal = document.getElementById('worker-modal');
        const title = document.getElementById('modal-title');
        const action = document.getElementById('form-action');
        
        modal.classList.remove('hidden');
        
        if (mode === 'edit') {
            title.innerText = '編輯員工';
            action.value = 'edit';
            document.getElementById('worker-id').value = data.id;
            document.getElementById('worker-name').value = data.name;
            document.getElementById('worker-phone').value = data.phone;
            document.getElementById('worker-salary-type').value = data.salary_type;
            document.getElementById('worker-salary-amount').value = data.salary_amount;
            document.getElementById('existing-id-card').value = data.id_card_path;
            document.getElementById('existing-safety-card').value = data.safety_card_path;
            
            if (data.id_card_path) document.getElementById('id-card-status').classList.remove('hidden');
            if (data.safety_card_path) document.getElementById('safety-card-status').classList.remove('hidden');
        } else {
            title.innerText = '新增員工';
            action.value = 'add';
            document.querySelector('form').reset();
            document.getElementById('id-card-status').classList.add('hidden');
            document.getElementById('safety-card-status').classList.add('hidden');
        }
    }

    function closeModal() {
        document.getElementById('worker-modal').classList.add('hidden');
    }
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
