<?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'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $stmt = $pdo->prepare("
        INSERT INTO project_phases
        (project_id, phase_name, budget, start_date, end_date, status)
        VALUES (?, ?, ?, ?, ?, 'PLANNED')
    ");

    $stmt->execute([
        $projectId,
        $_POST['phase_name'],
        $_POST['budget'] ?: null,
        $_POST['start_date'],
        $_POST['end_date']
    ]);

    header("Location: project_phases.php?project_id=" . $projectId);
    exit;
}

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

<div class="main-content">

<div class="page-header">
    <h2>Add Project Phase</h2>
</div>

<form method="POST" class="card-form">

    <input type="text" name="phase_name" placeholder="Phase Name" required>

    <input type="number" step="0.01" name="budget" placeholder="Budget (optional)">

    <label>Start Date</label>
    <input type="date" name="start_date" required>

    <label>End Date</label>
    <input type="date" name="end_date" required>

    <button type="submit" class="btn-primary">
        Save Phase
    </button>

</form>

</div>

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