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

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

requirePermission('view_projects');

if (!isset($_GET['id']) || (int)$_GET['id'] <= 0) {
    die("Project ID missing.");
}

$projectId = (int)$_GET['id'];

/* =============================
   FETCH PROJECT
============================= */

$stmt = $pdo->prepare("SELECT * FROM projects WHERE id = ?");
$stmt->execute([$projectId]);
$project = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$project) {
    die("Project not found.");
}

/* =============================
   FETCH TASKS
============================= */

$tasksStmt = $pdo->prepare("
    SELECT t.*,
           c.company_name,
           u.full_name
    FROM project_tasks t
    LEFT JOIN companies c ON t.assigned_company_id = c.id
    LEFT JOIN users u ON t.assigned_user_id = u.id
    WHERE t.project_id = ?
    ORDER BY t.id DESC
");
$tasksStmt->execute([$projectId]);
$tasks = $tasksStmt->fetchAll(PDO::FETCH_ASSOC);

/* =============================
   CALCULATE TOTALS + PROGRESS
============================= */

$totalRevenue = 0;
$totalCost    = 0;
$totalTasks   = count($tasks);
$completed    = 0;

foreach ($tasks as $t) {

    $qty = (float)$t['quantity'];
    $unitCost  = (float)$t['unit_cost'];
    $unitPrice = (float)$t['unit_price'];

    $totalRevenue += ($qty * $unitPrice);
    $totalCost    += ($qty * $unitCost);

    if ($t['status'] === 'DONE') {
        $completed++;
    }
}

$progress = ($totalTasks > 0)
    ? round(($completed / $totalTasks) * 100)
    : 0;

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

<div class="main-content">

  <div class="page-header">
      <h2><?= htmlspecialchars($project['project_name']) ?></h2>
      <p class="page-subtitle">
          <?= isset($project['client_name']) 
              ? "Client: " . htmlspecialchars($project['client_name']) 
              : "" ?>
      </p>
  </div>

  <!-- ================= PROJECT SUMMARY ================= -->
  <div class="dashboard-grid" style="margin-bottom:20px;">

      <div class="stat-card">
          <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 green">
          <h4>Profit</h4>
          <div class="number">
              R <?= number_format($totalRevenue - $totalCost,2) ?>
          </div>
      </div>

      <div class="stat-card blue">
          <h4>Progress</h4>
          <div class="number"><?= $progress ?>%</div>
      </div>

  </div>

  <!-- ================= PROGRESS BAR ================= -->
  <div style="background:#e5e5e5;height:10px;border-radius:8px;margin-bottom:20px;">
      <div style="width:<?= $progress ?>%;background:#f2531e;height:100%;border-radius:8px;"></div>
  </div>

  <!-- ================= ADD TASK BUTTON ================= -->
  <div style="margin-bottom:15px;">
      <a class="btn-primary"
         href="add_task.php?project_id=<?= $projectId ?>">
         + Add Task
      </a>
  </div>

  <!-- ================= TASK TABLE ================= -->
  <div class="table-wrap">
    <table>
        <thead>
            <tr>
                <th>Task</th>
                <th>Company</th>
                <th>User</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="8" style="text-align:center;">No tasks yet.</td>
            </tr>
        <?php else: ?>

        <?php foreach ($tasks as $t): 

            $lineRevenue = $t['quantity'] * $t['unit_price'];
            $lineCost    = $t['quantity'] * $t['unit_cost'];

            $statusColor = '#999';

if ($t['status'] === 'PENDING')      $statusColor = '#f59e0b';  // Orange
if ($t['status'] === 'ASSIGNED')     $statusColor = '#7c3aed';  // Purple
if ($t['status'] === 'IN_PROGRESS')  $statusColor = '#2563eb';  // Blue
if ($t['status'] === 'COMPLETED')    $statusColor = '#16a34a';  // Green
if ($t['status'] === 'CANCELLED')    $statusColor = '#dc2626';  // Red
        ?>
            <tr>
                <td>
                    <strong><?= htmlspecialchars($t['description']) ?></strong><br>
                    <small><?= htmlspecialchars($t['task_type']) ?></small>
                </td>

                <td><?= htmlspecialchars($t['company_name'] ?? '-') ?></td>
                <td><?= htmlspecialchars($t['full_name'] ?? '-') ?></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><?= $t['due_date'] ?: '-' ?></td>

                <td>R <?= number_format($lineRevenue,2) ?></td>
                <td>R <?= number_format($lineCost,2) ?></td>
                <td>
    <a class="btn-sm"
       href="edit_task.php?id=<?= $t['id'] ?>&project_id=<?= $projectId ?>">
       Edit
    </a>
</td>
            </tr>
        <?php endforeach; ?>

        <?php endif; ?>

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

</div>

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