<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Spa Bookings</title>
  <link rel="apple-touch-icon" sizes="76x76" href="../images/logo-tr.png">
  <link rel="icon" type="image/png" href="../images/logo-tr.png">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  
  <!-- AdminLTE CSS -->
  <link rel="stylesheet" href="plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="dist/css/adminlte.min.css">
  <style>
    .booking-card {
      border: 1px solid #ddd;
      border-radius: 10px;
      transition: 0.3s ease;
    }
    .booking-card:hover {
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
  </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<?php 
  include('menu_admin.php');
  include_once 'model/bookings_model.php';
  $bookings_model = new bookings_model();
  $bookings = $bookings_model->getActiveBookings();
?>
<div class="content-wrapper">
  <section class="content">
    <div class="container-fluid py-4">
      <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="mb-0">Spa Bookings</h3>
      </div>

      <div class="card">
  <div class="card-body table-responsive">
    <?php if (!empty($bookings)) : ?>
    <table class="table table-bordered table-hover">
      <thead class="thead-light">
        <tr>
          <th>#</th>
          <th>Customer</th>
          <th>Sex</th>
          <th>Phone</th>
          <th>Email</th>
          <th>Service</th>
          <th>Date</th>
          <th>Time</th>
          <th>Cost</th>
          <th>Notes</th>
          <th>Status</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($bookings as $i => $booking): ?>
          <tr>
            <td><?= $i + 1 ?></td>
            <td><?= htmlspecialchars($booking['fullname']) ?></td>
            <td><?= htmlspecialchars($booking['sex']) ?></td>
            <td><?= htmlspecialchars($booking['phone_number']) ?></td>
            <td><?= htmlspecialchars($booking['email']) ?></td>
            <td><?= htmlspecialchars($booking['service_name']) ?></td>
            <td><?= htmlspecialchars($booking['appointment_date']) ?></td>
            <td><?= htmlspecialchars($booking['time_slot']) ?></td>
            <td>R <?= htmlspecialchars($booking['cost']) ?></td>
            <td><?= htmlspecialchars($booking['booking_notes']) ?></td>
            <?php
              $today = date('Y-m-d');
              $appointment_date = $booking['appointment_date'];
              $status = $booking['booking_state'];
              $booking_id = $booking['id'];

              if ($status === 1) {
                  if ($appointment_date < $today) {
                      $bg_class = 'bg-danger text-white';
                      $status_notes = 'Expired Booking';
                  } else {
                      $bg_class = 'bg-info text-white';
                      $status_notes = 'Waiting for payment/Confirmation';
                  }
              } elseif ($status === 2) {
                  $bg_class = 'bg-success text-dark';
                  $status_notes = 'Confirmed Booking';
              } elseif ($status === 0) {
                  $bg_class = 'bg-danger text-white'; 
                  $status_notes = 'Cancelled Booking';
              } else {
                  $bg_class = '';
                  $status_notes = 'Unknown';
              }
              ?>

              <!-- Booking Status -->
              <td class="<?= $bg_class ?>"><?= htmlspecialchars($status_notes) ?></td>

              
<td>
  <button 
    class="btn btn-info booking-action-btn" 
    data-status="<?= $status ?>" 
    data-id="<?= $booking_id ?>"
    data-date="<?= $appointment_date ?>"
  >
    Action
  </button>
</td>



          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    <?php else: ?>
      <div class="alert alert-info">No bookings found.</div>
    <?php endif; ?>
  </div>
</div>

    </div>
  </section>
</div>

<!-- Scripts -->
<script src="plugins/jquery/jquery.min.js"></script>
<script src="plugins/jquery-ui/jquery-ui.min.js"></script>
<script src="plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.js"></script>
<script src="js/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>   

<script>
  document.addEventListener("DOMContentLoaded", function () {
    document.querySelectorAll(".booking-action-btn").forEach(button => {
      button.addEventListener("click", function () {
        const bookingId = this.dataset.id;
        const status = parseInt(this.dataset.status);
        const appointmentDate = this.dataset.date;

        // Logic to determine what options are available
        if (status === 1) {
          // "Awaiting payment/confirmation" - show options to confirm or cancel
          Swal.fire({
            title: "Booking Awaiting Confirmation",
            text: "Do you want to confirm or cancel this booking?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Confirm',
            cancelButtonText: 'Cancel Booking'
          }).then((result) => {
            if (result.isConfirmed) {
              // User chose to confirm the booking
              updateBookingStatus(bookingId, 'confirm');
            } else if (result.dismiss === Swal.DismissReason.cancel) {
              // User chose to cancel the booking
              updateBookingStatus(bookingId, 'cancel');
            }
          });
        } else if (status === 2) {
          // "Confirmed booking" - show info that no action is needed
          Swal.fire('Info', 'This booking has already been confirmed and paid for.', 'info');
        }
      });
    });
  });

  // Function to handle booking status update
  function updateBookingStatus(bookingId, action) {
    let url = '';
    let data = {
      booking_id: bookingId,
      action: action
    };

    if (action === 'confirm') {
      url = 'confirm_booking.php';  // URL to confirm the booking
    } else if (action === 'cancel') {
      url = 'cancel_booking.php';  // URL to cancel the booking
    }

    // AJAX request to update booking status
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams(data)
    })
    .then(response => response.json())
    .then(result => {
      if (result.success) {
        Swal.fire('Success', 'Booking status updated successfully!', 'success');
        location.reload();  // Optionally, reload the page to update the booking status
      } else {
        Swal.fire('Error', 'Failed to update booking status.', 'error');
      }
    })
    .catch(error => {
      Swal.fire('Error', 'Something went wrong. Please try again later.', 'error');
    });
  }
</script>


</body>
</html>
