<?php
require_once 'header.php';
require_permission('projects');

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header('Location: projects.php');
    exit;
}

$stmt = $mysqli->prepare('SELECT name, location, description, project_status FROM projects WHERE id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($name, $location, $description, $status);
if (!$stmt->fetch()) {
    $stmt->close();
    echo '<div class="alert alert-danger m-3">Projekt nije pronađen.</div>';
    require_once 'footer.php';
    exit;
}
$stmt->close();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $location = trim($_POST['location'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $status = $_POST['project_status'] ?? 'open';
    if ($status !== 'open' && $status !== 'closed') $status = 'open';

    if ($name === '') {
        echo '<div class="alert alert-danger m-3">Naziv je obavezan.</div>';
    } else {
        $stmtU = $mysqli->prepare('UPDATE projects SET name=?, location=?, description=?, project_status=? WHERE id=?');
        $stmtU->bind_param('ssssi', $name, $location, $description, $status, $id);
        $stmtU->execute();
        $stmtU->close();
        header('Location: projects.php?msg=' . urlencode('Projekt ažuriran.'));
        exit;
    }
}
?>
<div class="row g-3 mb-3">
    <div class="col">
        <div class="section-title">Uredi projekt</div>
    </div>
</div>
<div class="card card-soft">
    <div class="card-body card-soft-body">
        <form method="post">
            <div class="mb-2">
                <label class="form-label">Naziv</label>
                <input type="text" name="name" class="form-control" required
                       value="<?php echo htmlspecialchars($name); ?>">
            </div>
            <div class="mb-2">
                <label class="form-label">Lokacija</label>
                <input type="text" name="location" class="form-control"
                       value="<?php echo htmlspecialchars($location); ?>">
            </div>
            <div class="mb-2">
                <label class="form-label">Opis</label>
                <textarea name="description" class="form-control" rows="3"><?php echo htmlspecialchars($description); ?></textarea>
            </div>
            <div class="mb-2">
                <label class="form-label">Status</label>
                <select name="project_status" class="form-select form-select-sm">
                    <option value="open" <?php echo $status==='open'?'selected':''; ?>>Otvoren</option>
                    <option value="closed" <?php echo $status==='closed'?'selected':''; ?>>Dovršen</option>
                </select>
            </div>
            <button class="btn btn-primary btn-soft" type="submit">Spremi</button>
            <a href="projects.php" class="btn btn-outline-secondary btn-soft">Natrag</a>
        </form>
    </div>
</div>
<?php require_once 'footer.php'; ?>
