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

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

// 處理新增/編輯地盤
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $location = $_POST['location'] ?? '';
    $unit = $_POST['unit'] ?? '';
    $status = $_POST['status'] ?? 'active';
    $id = $_POST['id'] ?? null;

    if (!empty($location)) {
        if ($action === 'add') {
            $stmt = $pdo->prepare("INSERT INTO sites (location, unit, status) VALUES (?, ?, ?)");
            $stmt->execute([$location, $unit, $status]);
            $success = '地盤已成功新增';
        } elseif ($action === 'edit' && $id) {
            $stmt = $pdo->prepare("UPDATE sites SET location = ?, unit = ?, status = ? WHERE id = ?");
            $stmt->execute([$location, $unit, $status, $id]);
            $success = '地盤資料已更新';
        }
    } else {
        $error = '請填寫地點';
    }
}

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

// 獲取所有地盤
$sites = $pdo->query("SELECT * FROM sites 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-green-600 hover:bg-green-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; ?>

<!-- Site List -->
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php foreach ($sites as $site): ?>
    <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-100 hover:shadow-md transition">
        <div class="flex justify-between items-start mb-4">
            <div class="p-3 rounded-xl <?php echo $site['status'] === 'active' ? 'bg-green-50 text-green-600' : 'bg-slate-50 text-slate-400'; ?>">
                <i class="fas fa-building text-xl"></i>
            </div>
            <div class="flex gap-2">
                <button onclick='openModal("edit", <?php echo json_encode($site); ?>)' class="text-slate-400 hover:text-blue-600">
                    <i class="fas fa-edit"></i>
                </button>
                <a href="?delete=<?php echo $site['id']; ?>" onclick="return confirm('確定要刪除此地盤嗎？')" class="text-slate-400 hover:text-red-600">
                    <i class="fas fa-trash-alt"></i>
                </a>
            </div>
        </div>
        <h3 class="text-lg font-bold text-slate-800 mb-1"><?php echo htmlspecialchars($site['location']); ?></h3>
        <p class="text-slate-500 text-sm mb-4"><?php echo htmlspecialchars($site['unit'] ?: '無單位資訊'); ?></p>
        <div class="flex justify-between items-center pt-4 border-t border-slate-50">
            <span class="text-xs font-semibold px-2 py-1 rounded <?php echo $site['status'] === 'active' ? 'bg-green-100 text-green-600' : 'bg-slate-100 text-slate-500'; ?>">
                <?php echo $site['status'] === 'active' ? '進行中' : '已完工'; ?>
            </span>
            <a href="site_docs.php?site_id=<?php echo $site['id']; ?>" class="text-blue-500 text-sm font-medium hover:underline">
                查看文件 <i class="fas fa-chevron-right text-xs ml-1"></i>
            </a>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Modal -->
<div id="site-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-md p-8 shadow-2xl transform transition-all">
        <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="sites.php" method="POST" class="space-y-4">
            <input type="hidden" name="action" id="form-action" value="add">
            <input type="hidden" name="id" id="site-id">
            
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">地點 *</label>
                <input type="text" name="location" id="site-location" required placeholder="如：將軍澳天晉"
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-green-500 outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">單位</label>
                <input type="text" name="unit" id="site-unit" placeholder="如：1座 18樓 B室"
                    class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-green-500 outline-none">
            </div>
            <div>
                <label class="block text-sm font-medium text-slate-700 mb-1">狀態</label>
                <select name="status" id="site-status" class="w-full px-4 py-2 border border-slate-200 rounded-lg focus:ring-2 focus:ring-green-500 outline-none">
                    <option value="active">進行中</option>
                    <option value="completed">已完工</option>
                </select>
            </div>

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

<script>
    function openModal(mode, data = null) {
        const modal = document.getElementById('site-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('site-id').value = data.id;
            document.getElementById('site-location').value = data.location;
            document.getElementById('site-unit').value = data.unit;
            document.getElementById('site-status').value = data.status;
        } else {
            title.innerText = '新增地盤';
            action.value = 'add';
            document.querySelector('form').reset();
        }
    }

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

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