<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('projects.manage');

require_once __DIR__ . '/../config/database.php';

requirePermission('view_tasks');

$currentPage = basename($_SERVER['PHP_SELF']);

// Filters
$status     = trim($_GET['status'] ?? '');
$companyId  = (int)($_GET['company_id'] ?? 0);
$projectId  = (int)($_GET['project_id'] ?? 0);
$q          = trim($_GET['q'] ?? '');

// Companies dropdown
$companies = $pdo->query("
    SELECT id, company_name
    FROM companies
    WHERE status = 'ACTIVE'
    ORDER BY company_name ASC
")->fetchAll(PDO::FETCH_ASSOC);

// Projects dropdown
$projectsList = $pdo->query("
    SELECT id, project_name
    FROM projects
    ORDER BY created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

// Build WHERE safely
$where = [];
$params = [];

if ($status !== '') {
    $where[] = "t.status = ?";
    $params[] = $status;
}
if ($companyId > 0) {
    $where[] = "t.assigned_company_id = ?";
    $params[] = $companyId;
}
if ($projectId > 0) {
    $where[] = "t.project_id = ?";
    $params[] = $projectId;
}
if ($q !== '') {
    $where[] = "(t.description LIKE ? OR t.task_code LIKE ? OR p.project_name LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";

// Fetch tasks
$stmt = $pdo->prepare("
    SELECT
        t.*,
        p.project_name,
        p.client_name,
        c.company_name,
        u.full_name
    FROM project_tasks t
    LEFT JOIN projects p ON p.id = t.project_id
    LEFT JOIN companies c ON c.id = t.assigned_company_id
    LEFT JOIN users u ON u.id = t.assigned_user_id
    $whereSql
    ORDER BY t.id DESC
");
$stmt->execute($params);
$tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Totals
$totalRevenue = 0;
$totalCost = 0;
$done = 0;
$total = count($tasks);

foreach ($tasks as $t) {
    $qty = (float)($t['quantity'] ?? 0);
    $totalRevenue += $qty * (float)($t['unit_price'] ?? 0);
    $totalCost    += $qty * (float)($t['unit_cost'] ?? 0);
    if (($t['status'] ?? '') === 'DONE') $done++;
}

$profit = $totalRevenue - $totalCost;
$progress = $total > 0 ? round(($done / $total) * 100) : 0;

require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>

<div class="main-content">

  <div class="page-header">
    <h2>Task Board</h2>
    <p class="page-subtitle">All tasks across projects (Metering + Electrical Scope)</p>
  </div>

  <!-- Summary cards -->
  <div class="dashboard-grid" style="margin-bottom:16px;">
    <div class="stat-card">
      <h4>Tasks</h4>
      <div class="number"><?= (int)$total ?></div>
    </div>
    <div class="stat-card blue">
      <h4>Progress</h4>
      <div class="number"><?= (int)$progress ?>%</div>
    </div>
    <div class="stat-card green">
      <h4>Total Revenue</h4>
      <div class="number">R <?= number_format($totalRevenue, 2) ?></div>
    </div>
    <div class="stat-card red">
      <h4>Total Cost</h4>
      <div class="number">R <?= number_format($totalCost, 2) ?></div>
    </div>
    <div class="stat-card">
      <h4>Profit</h4>
      <div class="number">R <?= number_format($profit, 2) ?></div>
    </div>
  </div>

  <!-- Progress bar -->
  <div style="background:#e5e5e5;height:10px;border-radius:8px;margin-bottom:18px;">
    <div style="width:<?= (int)$progress ?>%;background:#f5511d;height:100%;border-radius:8px;"></div>
  </div>

  <!-- Actions -->
  <?php if (hasPermission('manage_tasks')): ?>
    <div style="margin-bottom:12px;">
      <a class="btn-primary" href="add_task.php">+ Add Task</a>
    </div>
  <?php endif; ?>

  <!-- Filters -->
  <form method="GET" style="display:flex;flex-wrap:wrap;gap:10px;margin-bottom:14px;">
    <input type="text" name="q" placeholder="Search task / project / code" value="<?= htmlspecialchars($q) ?>" style="max-width:260px;">

    <select name="status">
      <option value="">All Status</option>
      <?php foreach (['PENDING','ASSIGNED','IN_PROGRESS','DONE','BLOCKED'] as $s): ?>
        <option value="<?= $s ?>" <?= ($status===$s)?'selected':'' ?>><?= $s ?></option>
      <?php endforeach; ?>
    </select>

    <select name="company_id">
      <option value="">All Companies</option>
      <?php foreach ($companies as $c): ?>
        <option value="<?= (int)$c['id'] ?>" <?= ($companyId===(int)$c['id'])?'selected':'' ?>>
          <?= htmlspecialchars($c['company_name']) ?>
        </option>
      <?php endforeach; ?>
    </select>

    <select name="project_id">
      <option value="">All Projects</option>
      <?php foreach ($projectsList as $p): ?>
        <option value="<?= (int)$p['id'] ?>" <?= ($projectId===(int)$p['id'])?'selected':'' ?>>
          <?= htmlspecialchars($p['project_name']) ?>
        </option>
      <?php endforeach; ?>
    </select>

    <button type="submit" class="btn-primary">Filter</button>
    <a href="project_tasks.php" class="btn-secondary">Reset</a>
  </form>

  <!-- Table -->
  <div class="table-wrap">
    <table>
      <thead>
        <tr>
          <th>Task</th>
          <th>Project</th>
          <th>Installer</th>
          <th>Status</th>
          <th>Priority</th>
          <th>Due</th>
          <th>Revenue</th>
          <th>Cost</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>

      <?php if (empty($tasks)): ?>
        <tr>
          <td colspan="9" style="text-align:center;">No tasks found.</td>
        </tr>
      <?php else: ?>
        <?php foreach ($tasks as $t):
          $lineRevenue = (float)$t['quantity'] * (float)$t['unit_price'];
          $lineCost    = (float)$t['quantity'] * (float)$t['unit_cost'];

          $statusColor = '#999';
          if ($t['status'] === 'DONE')        $statusColor = '#16a34a';
          if ($t['status'] === 'IN_PROGRESS') $statusColor = '#2563eb';
          if ($t['status'] === 'BLOCKED')     $statusColor = '#dc2626';
          if ($t['status'] === 'PENDING')     $statusColor = '#f59e0b';
        ?>
          <tr>
            <td>
              <strong><?= htmlspecialchars($t['description']) ?></strong><br>
              <small><?= htmlspecialchars($t['task_type'] ?? '') ?> <?= $t['task_code'] ? ' • '.htmlspecialchars($t['task_code']) : '' ?></small>
            </td>

            <td>
              <?= htmlspecialchars($t['project_name'] ?? '-') ?><br>
              <small><?= htmlspecialchars($t['client_name'] ?? '') ?></small>
            </td>

            <td>
              <?= htmlspecialchars($t['company_name'] ?? '-') ?><br>
              <small><?= htmlspecialchars($t['full_name'] ?? '-') ?></small>
            </td>

            <td>
              <span style="background:<?= $statusColor ?>;color:#fff;padding:4px 8px;border-radius:6px;font-size:12px;">
                <?= htmlspecialchars($t['status'] ?? '') ?>
              </span>
            </td>

            <td><?= htmlspecialchars($t['priority'] ?? '') ?></td>
            <td><?= htmlspecialchars($t['due_date'] ?: '-') ?></td>
            <td>R <?= number_format($lineRevenue,2) ?></td>
            <td>R <?= number_format($lineCost,2) ?></td>
            <td>
              <a href="project_view.php?id=<?= (int)$t['project_id'] ?>">View</a>
            </td>
          </tr>
        <?php endforeach; ?>
      <?php endif; ?>

      </tbody>
    </table>
  </div>

</div>

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