<?php
session_start();
require_once '../includes/config.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'controller') {
    header("Location: ../auth/login.php");
    exit;
}

$controller_id = $_SESSION['user_id'];
$id = $_GET['id'] ?? null;

if (!$id) {
    header("Location: view_occurrences.php");
    exit;
}

// Fetch existing
$stmt = $pdo->prepare("SELECT * FROM occurrences WHERE id = ? AND controller_id = ?");
$stmt->execute([$id, $controller_id]);
$occurrence = $stmt->fetch();

if (!$occurrence) {
    die("Occurrence not found or unauthorized.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title']);
    $details = trim($_POST['details']);

    if ($title && $details) {
        $update = $pdo->prepare("UPDATE occurrences SET title = ?, details = ? WHERE id = ? AND controller_id = ?");
        if ($update->execute([$title, $details, $id, $controller_id])) {
            $success = "Occurrence updated successfully.";
        } else {
            $error = "Update failed.";
        }
    } else {
        $error = "Title and details cannot be empty.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Edit Occurrence</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
  <h4>Edit Occurrence</h4>
  <?php if (!empty($success)): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php elseif (!empty($error)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <form method="post">
    <div class="mb-3">
      <label class="form-label">Title</label>
      <input type="text" name="title" class="form-control" required value="<?= htmlspecialchars($occurrence['title']) ?>">
    </div>
    <div class="mb-3">
      <label class="form-label">Details</label>
      <textarea name="details" class="form-control" rows="5" required><?= htmlspecialchars($occurrence['details']) ?></textarea>
    </div>
    <button type="submit" class="btn btn-primary">Update</button>
    <a href="view_occurrences.php" class="btn btn-secondary">Back</a>
  </form>
</div>
</body>
</html>
