<?php
ob_start();
$assmentId = $_GET['id'];
$pdo = new PDO('mysql:host=localhost;dbname=meetup', 'root', '');

$stmt = $pdo->prepare('SELECT * FROM goaltargets WHERE id = :id');
$stmt->execute(['id' => $assmentId]);
$goalandtarget = $stmt->fetch(PDO::FETCH_ASSOC);
?>

<main class="container-fluid px-6 pb-10">
  <header class="py-4 border-bottom">
    <h3 class="h4 ls-tight">Update Goals and Targets</h3>
  </header>

  <div id="responseMessage" class="my-3"></div>

  <form id="updateAssessmentForm">
    <input type="hidden" id="id" name="id" value="<?= $goalandtarget['id']; ?>">

    <div class="row g-3 mt-6">
      <div class="col-md-4">
          <label class="form-label">Title</label>
          <input type="text" name="title" class="form-control" value="<?= $goalandtarget['title']; ?>"  required>
        </div>
        <div class="col-md-4">
          <label class="form-label">Created By</label>
          <input type="text" name="createdby" class="form-control" value="<?= $goalandtarget['createdby']; ?>"  required>
        </div>
        <div class="col-md-4">
          <label class="form-label">Image</label>
          <input type="file" name="image" class="form-control" >
          <img src="<?= $goalandtarget['image']; ?>" alt="Goal Image" width="60" height="60">
        </div>
    </div>
    <div class="float-end mt-4">
      <button class="btn btn-success text-white" type="submit">Update</button>
    </div>
  </form>
</main>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $(document).ready(function () {
    $('#updateAssessmentForm').on('submit', function (e) {
      e.preventDefault();

      const formData = new FormData(this);

      $.ajax({
        url: 'http://localhost/gomeetapi/update/goals/targets',
        type: 'POST', // use POST
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
          let res;
          try {
            res = typeof response === 'string' ? JSON.parse(response) : response;
          } catch (e) {
            $('#responseMessage').html('<div class="alert alert-danger">Invalid JSON from server</div>');
            return;
          }

          if (res.Result === "true") {
            $('#responseMessage').html('<div class="alert alert-success">' + res.ResponseMsg + '</div>');
            setTimeout(() => window.location.href = 'goalsandtarget.php', 1500);
          } else {
            $('#responseMessage').html('<div class="alert alert-danger">' + res.ResponseMsg + '</div>');
          }
        },
        error: function (xhr, status, error) {
          $('#responseMessage').html('<div class="alert alert-danger">AJAX error: ' + error + '</div>');
        }
      });
    });
  }); 
</script>


<?php
$content = ob_get_clean();
include '../layouts/master.php';
