<?php
require_once __DIR__ . '/../../../app/Models/Journal.php';
$model = new Journal();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $j = $model->getById((int)$_GET['id']);
    if (!$j) { echo "<p class='text-danger'>Journal not found</p>"; exit; }
?>
<form id="editJournalForm">
  <input type="hidden" name="id" value="<?= $j['id'] ?>">
  <div class="form-row">
    <div class="form-group col-md-4">
      <label>Reference No</label>
      <input type="text" name="reference_no" class="form-control" value="<?= htmlspecialchars($j['reference_no']) ?>">
    </div>
    <div class="form-group col-md-4">
      <label>Date</label>
      <input type="date" name="journal_date" class="form-control" value="<?= htmlspecialchars($j['journal_date']) ?>" required>
    </div>
    <div class="form-group col-md-4">
      <label>Status</label>
      <select name="status" class="form-control">
        <option value="draft" <?= $j['status']=='draft'?'selected':'' ?>>Draft</option>
        <option value="posted" <?= $j['status']=='posted'?'selected':'' ?>>Posted</option>
      </select>
    </div>
  </div>
  <div class="form-group">
    <label>Description</label>
    <textarea name="description" rows="3" class="form-control"><?= htmlspecialchars($j['description']) ?></textarea>
  </div>
  <button type="submit" class="btn btn-warning btn-block">Update</button>
</form>

<script>
$('#editJournalForm').on('submit', function(e){
  e.preventDefault();
  $.post('ajax/journal/edit.php', $(this).serialize(), function(){
    $('#editJournalModal').modal('hide');
    location.reload();
  });
});
</script>
<?php
exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $model->update((int)$_POST['id'], $_POST);
    echo 'updated';
}
