<?php
session_start();
require 'db/config.php';
$db = db();

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

$role = $_SESSION['role'];
$userId = $_SESSION['user_id'];

// Fetch all operations with context
$sql = "
    SELECT o.*, c.name as component_name, j.name as job_name, j.serial_number, u.name as worker_name
    FROM operations o
    JOIN components c ON o.component_id = c.id
    JOIN jobs j ON c.job_id = j.id
    LEFT JOIN users u ON o.assigned_worker_id = u.id
    WHERE o.status != 'completed'
    ORDER BY o.priority_tier DESC, o.order_index ASC, o.created_at ASC
";
$operations = $db->query($sql)->fetchAll();

// Group by status for Kanban
$kanban = [
    'pending' => [],
    'in_progress' => [],
    'stalled' => []
];

foreach ($operations as $op) {
    if (isset($kanban[$op['status']])) {
        $kanban[$op['status']][] = $op;
    }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>M-TRACK | Shop Floor</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --bg: #f8fafc;
      --card-bg: #ffffff;
      --primary: #1e293b;
      --accent: #3b82f6;
      --text: #334155;
      --sidebar-w: 260px;
    }
    body { font-family: 'Inter', sans-serif; background-color: var(--bg); color: var(--text); overflow-x: hidden; }
    .sidebar { width: var(--sidebar-w); position: fixed; top: 0; bottom: 0; left: 0; background: var(--card-bg); border-right: 1px solid #e2e8f0; padding: 2rem 1.5rem; z-index: 10; }
    .main-content { margin-left: var(--sidebar-w); padding: 2rem; min-height: 100vh; }
    .top-bar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; }
    .kanban-board { display: flex; gap: 1.5rem; align-items: flex-start; overflow-x: auto; padding-bottom: 1rem; }
    .kanban-col { background: #e2e8f0; border-radius: 12px; min-width: 320px; padding: 1rem; flex-shrink: 0; }
    .kanban-card { background: white; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 2px 4px rgba(0,0,0,0.05); cursor: grab; border-left: 4px solid var(--accent); transition: transform 0.2s; }
    .kanban-card:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    .kanban-card.stalled { border-left-color: #ef4444; }
    .kanban-card.in_progress { border-left-color: #10b981; }
    .kanban-title { font-weight: 600; font-size: 0.95rem; margin-bottom: 0.25rem; color: var(--primary); }
    .kanban-meta { font-size: 0.8rem; color: #64748b; }
    .badge-tier { font-size: 0.7rem; padding: 0.25em 0.5em; border-radius: 4px; font-weight: 600; text-transform: uppercase; }
    .tier-urgent { background: #fee2e2; color: #b91c1c; }
    .tier-high { background: #fef3c7; color: #c2410c; }
    .tier-normal { background: #f1f5f9; color: #475569; }
    .tier-low { background: #f8fafc; color: #94a3b8; border: 1px solid #e2e8f0; }
  </style>
</head>
<body>

<div class="sidebar">
  <h4 class="fw-bold mb-5" style="color: var(--primary);"><i class="bi bi-cpu me-2"></i>M-TRACK</h4>
  <nav class="nav nav-pills flex-column">
    <a class="nav-link" href="dashboard.php"><i class="bi bi-grid-fill me-2"></i> Dashboard</a>
    <?php if ($role === 'admin'): ?>
      <a class="nav-link" href="jobs.php"><i class="bi bi-briefcase me-2"></i> Jobs</a>
      <a class="nav-link active" href="shop_floor.php"><i class="bi bi-kanban me-2"></i> Shop Floor</a>
      <a class="nav-link" href="inventory.php"><i class="bi bi-boxes me-2"></i> Inventory</a>
      <a class="nav-link" href="users.php"><i class="bi bi-people me-2"></i> Users</a>
      <a class="nav-link" href="time_study.php"><i class="bi bi-clock-history me-2"></i> Time Study</a>
    <?php else: ?>
      <a class="nav-link" href="dashboard.php"><i class="bi bi-list-task me-2"></i> My Queue</a>
      <a class="nav-link active" href="shop_floor.php"><i class="bi bi-kanban me-2"></i> Board View</a>
    <?php endif; ?>
    <hr class="my-4 border-secondary opacity-25">
    <a class="nav-link text-danger" href="logout.php"><i class="bi bi-box-arrow-right me-2"></i> Logout</a>
  </nav>
</div>

<div class="main-content">
  <div class="top-bar">
    <div>
      <h2 class="h3 fw-bold mb-1">Shop Floor</h2>
      <p class="text-muted mb-0">Drag and drop operations to update status</p>
    </div>
  </div>

  <div class="kanban-board">
    
    <!-- Pending Column -->
    <div class="kanban-col">
      <h5 class="fw-bold mb-3 px-2">Pending <span class="badge bg-secondary rounded-pill float-end"><?= count($kanban['pending']) ?></span></h5>
      <?php foreach ($kanban['pending'] as $op): ?>
        <div class="kanban-card">
          <div class="d-flex justify-content-between mb-1">
            <span class="badge-tier tier-<?= $op['priority_tier'] ?>"><?= $op['priority_tier'] ?></span>
            <span class="badge bg-light text-dark border"><i class="bi bi-tag"></i> <?= htmlspecialchars($op['process_type']) ?></span>
          </div>
          <div class="kanban-title"><?= htmlspecialchars($op['name']) ?></div>
          <div class="kanban-meta mb-2">
            <div><i class="bi bi-box"></i> <?= htmlspecialchars($op['component_name']) ?></div>
            <div><i class="bi bi-briefcase"></i> <?= htmlspecialchars($op['job_name']) ?> (<?= htmlspecialchars($op['serial_number']) ?>)</div>
          </div>
          <div class="mt-2 text-end">
            <button class="btn btn-sm btn-outline-primary rounded-pill px-3">Start</button>
          </div>
        </div>
      <?php endforeach; ?>
      <?php if (empty($kanban['pending'])): ?>
        <div class="text-muted text-center p-3 small">No pending operations</div>
      <?php endif; ?>
    </div>

    <!-- In Progress Column -->
    <div class="kanban-col">
      <h5 class="fw-bold mb-3 px-2">In Progress <span class="badge bg-success rounded-pill float-end"><?= count($kanban['in_progress']) ?></span></h5>
      <?php foreach ($kanban['in_progress'] as $op): ?>
        <div class="kanban-card in_progress">
          <div class="d-flex justify-content-between mb-1">
            <span class="badge-tier tier-<?= $op['priority_tier'] ?>"><?= $op['priority_tier'] ?></span>
            <span class="badge bg-light text-dark border"><i class="bi bi-person"></i> <?= htmlspecialchars($op['worker_name'] ?? 'Unknown') ?></span>
          </div>
          <div class="kanban-title"><?= htmlspecialchars($op['name']) ?></div>
          <div class="kanban-meta mb-2">
            <div><i class="bi bi-box"></i> <?= htmlspecialchars($op['component_name']) ?></div>
            <div><i class="bi bi-briefcase"></i> <?= htmlspecialchars($op['job_name']) ?> (<?= htmlspecialchars($op['serial_number']) ?>)</div>
          </div>
          <div class="mt-2 d-flex justify-content-between">
             <button class="btn btn-sm btn-outline-danger rounded-pill px-3">Stall</button>
             <button class="btn btn-sm btn-success rounded-pill px-3">Done</button>
          </div>
        </div>
      <?php endforeach; ?>
      <?php if (empty($kanban['in_progress'])): ?>
        <div class="text-muted text-center p-3 small">No operations in progress</div>
      <?php endif; ?>
    </div>

    <!-- Stalled Column -->
    <div class="kanban-col">
      <h5 class="fw-bold mb-3 px-2">Stalled <span class="badge bg-danger rounded-pill float-end"><?= count($kanban['stalled']) ?></span></h5>
      <?php foreach ($kanban['stalled'] as $op): ?>
        <div class="kanban-card stalled">
          <div class="d-flex justify-content-between mb-1">
            <span class="badge-tier tier-<?= $op['priority_tier'] ?>"><?= $op['priority_tier'] ?></span>
            <span class="badge bg-light text-dark border"><i class="bi bi-exclamation-triangle"></i> Issue</span>
          </div>
          <div class="kanban-title"><?= htmlspecialchars($op['name']) ?></div>
          <div class="kanban-meta mb-2">
            <div><i class="bi bi-box"></i> <?= htmlspecialchars($op['component_name']) ?></div>
            <div class="text-danger mt-1"><i class="bi bi-chat-dots"></i> <?= htmlspecialchars($op['blocked_reason'] ?? 'No reason provided') ?></div>
          </div>
          <div class="mt-2 text-end">
             <button class="btn btn-sm btn-outline-secondary rounded-pill px-3">Resume</button>
          </div>
        </div>
      <?php endforeach; ?>
      <?php if (empty($kanban['stalled'])): ?>
        <div class="text-muted text-center p-3 small">No stalled operations</div>
      <?php endif; ?>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
