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

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

requirePermission('manage_projects');

if (!isset($_GET['project_id'])) {
    die("Project ID missing.");
}

$projectId = (int)$_GET['project_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 PHASES
============================= */

$stmt = $pdo->prepare("
    SELECT * FROM project_phases
    WHERE project_id = ?
    ORDER BY start_date ASC
");
$stmt->execute([$projectId]);

$phases = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

<div class="main-content">

<div class="page-header">
    <h2>Project Phases</h2>
    <p class="page-subtitle">
        <?= htmlspecialchars($project['project_name']) ?>
    </p>
</div>

<div class="topbar" style="margin-bottom:18px;">
    <a href="add_phase.php?project_id=<?= $projectId ?>" class="btn-primary">
        + Add Phase
    </a>
</div>

<div class="table-wrap">
<table>
<thead>
<tr>
<th>Phase</th>
<th>Budget</th>
<th>Status</th>
<th>Start</th>
<th>End</th>
<th>Action</th>
</tr>
</thead>

<tbody>

<?php foreach ($phases as $p): ?>
<tr>
<td><?= htmlspecialchars($p['phase_name']) ?></td>
<td>
    <?= $p['budget'] ? 'R ' . number_format($p['budget'],2) : '-' ?>
</td>
<td>
    <span class="status-badge <?= strtolower($p['status']) ?>">
        <?= $p['status'] ?>
    </span>
</td>
<td><?= $p['start_date'] ?></td>
<td><?= $p['end_date'] ?></td>
<td>
    <a href="edit_phase.php?id=<?= $p['id'] ?>" class="action-link">Edit</a>
</td>
</tr>
<?php endforeach; ?>

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

</div>

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