<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/i18n.php';
auth_require_login();
$page_title = 'Projects Board';
$pdo = crm_pdo();

$role = gp_user_role($pdo);
$userId = gp_current_user_id();

$projectModel = new ProjectModel($pdo);
$rows = $projectModel->getListForRole($role, $userId);

$allStatuses = gp_project_statuses($pdo);

// Group projects by status code
$board = [];
foreach ($allStatuses as $code => $label) {
    if (trim((string)$code) === '') continue;
    $board[$code] = ['label' => $label, 'items' => []];
}
// Fallback column for projects with unknown status
$board['unknown'] = ['label' => 'Χωρίς Κατάσταση', 'items' => []];

foreach ($rows as $r) {
    $s = trim((string)$r['status']);
    if (isset($board[$s])) {
        $board[$s]['items'][] = $r;
    } else {
        $board['unknown']['items'][] = $r;
    }
}
if (empty($board['unknown']['items'])) {
    unset($board['unknown']);
}

include __DIR__ . '/../includes/header.php';
?>
<style>
.board-container { display:flex; gap:16px; overflow-x:auto; padding-bottom:16px; min-height:600px; align-items:flex-start; }
.board-column { flex: 0 0 320px; background:var(--gp-nav-bg-2); border-radius:16px; display:flex; flex-direction:column; padding:12px; border:1px solid var(--gp-card-border); }
.board-column-header { display:flex; justify-content:space-between; align-items:center; padding:0 8px 12px 8px; font-weight:700; color:var(--gp-text); text-transform:uppercase; letter-spacing:0.03em; font-size:0.85rem; }
.board-column-count { background:rgba(0,0,0,0.06); padding:2px 8px; border-radius:99px; font-size:0.75rem; }
:root[data-theme='dark'] .board-column-count { background:rgba(255,255,255,0.1); }
.board-cards-wrap { min-height: 50px; display:flex; flex-direction:column; gap:10px; }
.board-card { background:var(--gp-card-bg); border:1px solid var(--gp-card-border); border-radius:12px; padding:16px; cursor:grab; box-shadow:0 2px 8px rgba(0,0,0,0.03); transition: transform 0.2s, box-shadow 0.2s; }
.board-card:active { cursor:grabbing; }
.board-card:hover { transform:translateY(-2px); box-shadow:0 6px 16px rgba(0,0,0,0.08); }
.board-card-title { font-weight:700; font-size:0.95rem; line-height:1.2; margin-bottom:4px; }
.board-card-title a { color:var(--gp-text); text-decoration:none; }
.board-card-code { font-size:0.75rem; color:var(--gp-primary); font-weight:700; margin-bottom:8px; }
.board-card-customer { font-size:0.8rem; color:var(--gp-muted); display:flex; align-items:center; gap:4px; }
.sortable-ghost { opacity: 0.4; }
.projects-header-actions { display:flex; gap:12px; align-items:center; }
.view-toggle { display:flex; background:var(--gp-nav-bg-2); border-radius:8px; padding:4px; border:1px solid var(--gp-card-border); }
.view-toggle a { padding:6px 12px; text-decoration:none; color:var(--gp-muted); font-size:0.85rem; font-weight:600; border-radius:6px; }
.view-toggle a.active { background:var(--gp-card-bg); color:var(--gp-text); box-shadow:0 2px 4px rgba(0,0,0,0.05); }
</style>

<div class="page-header">
  <div class="page-header-title">
    <h1>📋 Πίνακας Έργων</h1>
    <span>Σύρετε τις κάρτες για αλλαγή κατάστασης</span>
  </div>
  <div class="projects-header-actions">
    <div class="view-toggle">
        <a href="index.php">Λίστα</a>
        <a href="board.php" class="active">Πίνακας</a>
    </div>
    <?php if (gp_can_create_project($pdo)): ?>
      <a class="btn btn-primary btn-sm" href="edit.php">+ Νέο Έργο</a>
    <?php endif; ?>
  </div>
</div>


<div class="board-container">
    <?php foreach ($board as $code => $col): ?>
    <div class="board-column">
        <div class="board-column-header">
            <span><?php echo h($col['label']); ?></span>
            <span class="board-column-count" data-col-count="<?php echo h($code); ?>"><?php echo count($col['items']); ?></span>
        </div>
        <div class="board-cards-wrap" data-status-code="<?php echo h($code); ?>">
            <?php foreach ($col['items'] as $item): ?>
            <div class="board-card" data-project-id="<?php echo (int)$item['id']; ?>">
                <div class="board-card-code">#<?php echo h($item['code']); ?></div>
                <div class="board-card-title"><a href="edit.php?id=<?php echo (int)$item['id']; ?>"><?php echo h($item['title']); ?></a></div>
                <div class="board-card-customer">👤 <?php echo h($item['customer_name']); ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Load SortableJS from CDN -->
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    const columns = document.querySelectorAll('.board-cards-wrap');
    
    columns.forEach(col => {
        new Sortable(col, {
            group: 'shared', 
            animation: 150,
            ghostClass: 'sortable-ghost',
            onEnd: function (evt) {
                const itemEl = evt.item;
                const newCol = evt.to;
                const oldCol = evt.from;
                
                if (newCol === oldCol) return; // Didn't change column
                
                const projectId = itemEl.getAttribute('data-project-id');
                const newStatus = newCol.getAttribute('data-status-code');
                const oldStatus = oldCol.getAttribute('data-status-code');
                
                // Update counts visually immediately
                updateCounts();
                
                // Fire AJAX to update DB
                fetch('/gopools/public/api/project_status_update.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        project_id: projectId,
                        status: newStatus,
                        csrf_token: window.csrfToken
                    })
                }).then(r => r.json()).then(data => {
                    if (!data.ok) {
                        alert('Failed to update status: ' + (data.error || 'Unknown error'));
                        // Revert visually if failed
                        oldCol.appendChild(itemEl);
                        updateCounts();
                    }
                }).catch(err => {
                    alert('Network error updating status.');
                    oldCol.appendChild(itemEl);
                    updateCounts();
                });
            }
        });
    });
    
    function updateCounts() {
        document.querySelectorAll('.board-column').forEach(col => {
            const wrap = col.querySelector('.board-cards-wrap');
            const countBadge = col.querySelector('.board-column-count');
            if (wrap && countBadge) {
                countBadge.innerText = wrap.children.length;
            }
        });
    }
});
</script>

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