<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Spa Services</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>
    .service-card {
      border: 1px solid #ddd;
      border-radius: 10px;
      transition: 0.3s ease;
    }
    .service-card:hover {
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    .service-card img {
      max-height: 250px;
      object-fit: cover;
      width: 100%;
      border-radius: 10px 10px 0 0;
    }
  </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<?php 
  include('menu_admin.php');
  include_once 'model/services_model.php';
  $services_model = new services_model();
  $services = $services_model->getServices();
?>
<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 Services</h3>
        <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addServiceModal">
  <i class="fas fa-plus-circle me-1"></i> Add New Service
</button>


      </div>

      <div class="row">
        <?php if (!empty($services)) : ?>
          <?php foreach($services as $service): ?>
            <div class="col-md-4 mb-4">
              <div class="card service-card h-100">
                <img src="../images/services/<?= htmlspecialchars($service['service_image']) ?>" alt="<?= htmlspecialchars($service['service_name']) ?>">
                <div class="card-body">
                  <h5 class="card-title"><?= htmlspecialchars($service['service_name']) ?></h5><br>
                  <p class="text-muted"><?= htmlspecialchars($service['short_description']) ?></p>
                  <p><strong>Duration:</strong> <?= htmlspecialchars($service['duration']) ?></p>
                  <p><strong>Price:</strong> R <?= htmlspecialchars($service['service_cost']) ?></p>
                  <div class="d-flex justify-content-end">
                    <button class="btn btn-sm btn-outline-secondary me-2" 
        onclick='openEditModal(<?= json_encode($service, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>)'>
  <i class="fas fa-edit"></i>
</button>

                    <a href="#" class="btn btn-sm btn-outline-danger delete-service-btn" data-code="<?= htmlspecialchars($service['service_code']) ?>">
  <i class="fas fa-trash-alt"></i>
</a>
                  </div>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php else : ?>
          <div class="col-12">
            <div class="alert alert-info">No services found.</div>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </section>

  <!-- Edit Service Modal -->
<div class="modal fade" id="editServiceModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form id="editServiceForm" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">Edit Service</h5>
          <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
          <input type="hidden" id="edit_service_code" name="service_code">

          <div class="mb-3">
            <label for="edit_service_name" class="form-label">Service Name</label>
            <input type="text" class="form-control" id="edit_service_name" name="service_name" required>
          </div>

          <div class="mb-3">
            <label for="edit_short_description" class="form-label">Short Description</label>
            <textarea class="form-control" id="edit_short_description" name="short_description" rows="2" required></textarea>
          </div>

          <div class="mb-3">
            <label for="edit_full_description" class="form-label">Full Description</label>
            <textarea class="form-control" id="edit_full_description" name="full_description" rows="4" required></textarea>
          </div>

          <div class="mb-3">
            <label for="edit_duration" class="form-label">Service Duration</label>
            <input type="text" class="form-control" id="edit_duration" name="service_duration" placeholder="e.g. 60 min" required>
          </div>

          <div class="mb-3">
            <label for="edit_service_cost" class="form-label">Service Cost</label>
            <input type="number" step="0.01" class="form-control" id="edit_service_cost" name="service_cost" required>
          </div>

          <div class="mb-3">
            <label for="edit_service_image" class="form-label">Service Image <small class="text-muted">(required)</small></label>
            <input type="file" class="form-control" id="edit_service_image" name="service_image" accept="image/*">
            <div class="mt-2">
              <img id="image_preview" src="#" alt="Preview" style="max-height: 150px; display: none;" class="rounded border">
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Save Changes</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>

        </div>
      </form>
    </div>
  </div>
</div>

<!-- Add Service Modal -->
<div class="modal fade" id="addServiceModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">
      <form id="addServiceForm" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">Add New Service</h5>
          <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
          <div class="mb-3">
            <label for="add_service_name" class="form-label">Service Name</label>
            <input type="text" class="form-control" id="add_service_name" name="service_name" required>
          </div>

          <div class="mb-3">
            <label for="add_short_description" class="form-label">Short Description</label>
            <textarea class="form-control" id="add_short_description" name="short_description" rows="2" required></textarea>
          </div>

          <div class="mb-3">
            <label for="add_full_description" class="form-label">Full Description</label>
            <textarea class="form-control" id="add_full_description" name="full_description" rows="4" required></textarea>
          </div>

          <div class="mb-3">
            <label for="add_duration" class="form-label">Service Duration</label>
            <input type="text" class="form-control" id="add_duration" name="service_duration" placeholder="e.g. 60 min" required>
          </div>

          <div class="mb-3">
            <label for="add_service_cost" class="form-label">Service Cost</label>
            <input type="number" step="0.01" class="form-control" id="add_service_cost" name="service_cost" required>
          </div>

          <div class="mb-3">
            <label for="add_service_image" class="form-label">Service Image <small class="text-muted">(required)</small></label>
            <input type="file" class="form-control" id="add_service_image" name="service_image" accept="image/*" required>
            <div class="mt-2">
              <img id="add_image_preview" src="#" alt="Preview" style="max-height: 150px; display: none;" class="rounded border">
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Add Service</button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>



</div>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark"></aside>

<!-- 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>
function openEditModal(service) {
  document.getElementById("edit_service_code").value = service.service_code;
  document.getElementById("edit_service_name").value = service.service_name;
  document.getElementById("edit_short_description").value = service.short_description;
  document.getElementById("edit_full_description").value = service.full_description;
  document.getElementById("edit_duration").value = service.duration || service.service_duration;
  document.getElementById("edit_service_cost").value = service.service_cost;

  const preview = document.getElementById("image_preview");
  preview.src = "images/services/" + service.service_image;
  preview.style.display = 'block';

  const modal = new bootstrap.Modal(document.getElementById('editServiceModal'));
  modal.show();
}


// Submit form via AJAX
document.getElementById("editServiceForm").addEventListener("submit", function(e) {
  e.preventDefault();

  const formData = new FormData(this);

  Swal.fire({
    title: 'Updating service...',
    didOpen: () => {
      Swal.showLoading();
    },
    allowOutsideClick: false
  });

  fetch('update_service.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    Swal.close();
    if (data.success) {
      Swal.fire({
        icon: 'success',
        title: 'Service updated!',
        showConfirmButton: false,
        timer: 1500
      }).then(() => location.reload());
    } else {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: data.message || 'Something went wrong'
      });
    }
  })
  .catch(err => {
    Swal.close();
    console.error("Error:", err);
    Swal.fire({
      icon: 'error',
      title: 'Error',
      text: 'Something went wrong'
    });
  });
});
</script>
<script>
document.getElementById('edit_service_image').addEventListener('change', function (e) {
  const reader = new FileReader();
  reader.onload = function (event) {
    const preview = document.getElementById('image_preview');
    preview.src = event.target.result;
    preview.style.display = 'block';
  };
  if (e.target.files[0]) {
    reader.readAsDataURL(e.target.files[0]);
  }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
  document.querySelectorAll('.delete-service-btn').forEach(button => {
    button.addEventListener('click', function(e) {
      e.preventDefault();
      const serviceCode = this.getAttribute('data-code');

      Swal.fire({
        title: 'Are you sure?',
        text: "This will mark the service as deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, delete it!',
        reverseButtons: true
      }).then((result) => {
        if (result.isConfirmed) {
          fetch('soft_delete_service.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ service_code: serviceCode })
          })
          .then(response => response.json())
          .then(data => {
            if(data.success){
              Swal.fire(
                'Deleted!',
                'The service has been marked as deleted.',
                'success'
              ).then(() => location.reload());
            } else {
              Swal.fire('Error!', data.message || 'Failed to delete.', 'error');
            }
          })
          .catch(() => {
            Swal.fire('Error!', 'Server error.', 'error');
          });
        }
      });
    });
  });
</script>




<script>
  // Image preview for Add Service Modal
  document.getElementById('add_service_image').addEventListener('change', function (e) {
    const reader = new FileReader();
    reader.onload = function (event) {
      const preview = document.getElementById('add_image_preview');
      preview.src = event.target.result;
      preview.style.display = 'block';
    };
    if (e.target.files[0]) {
      reader.readAsDataURL(e.target.files[0]);
    }
  });

  // Submit Add Service Form via AJAX
  document.getElementById('addServiceForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    fetch('add_service.php', { // adjust path if needed
      method: 'POST',
      body: formData
    })
    .then(res => res.json())
    .then(data => {
      if(data.success){
        Swal.fire({
          icon: 'success',
          title: 'Service added!',
          showConfirmButton: false,
          timer: 1500
        }).then(() => location.reload());
      } else {
        Swal.fire('Error', data.message || 'Failed to add service', 'error');
      }
    })
    .catch(() => {
      Swal.fire('Error', 'Server error, please try again later.', 'error');
    });
  });
</script>




</body>
</html>
