<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech
include('include/header.php');
$page_title = WEB_NAME . " | Logs Categories";

try {
    $stmt = $pdo->query("SELECT * FROM sm_categories ORDER BY id DESC");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $categories = [];
    error_log("Logs Categories fetch error: " . $e->getMessage());
}
?>
<title>Logs Categories - <?php echo $site_data['web_name']; ?></title>

<link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">

<style>
  .category-img {
    width: 50px; height: 50px;
    object-fit: contain;
    border: 1px solid #e3e6f0;
    border-radius: 8px;
    padding: 4px;
    background: white;
  }
  .btn-group { white-space: nowrap; }
  .dropdown-item { cursor: pointer; }
  .dropdown-item i { width: 20px; margin-right: 5px; }
</style>

<div class="container-fluid" id="container-wrapper">
  <div class="d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 text-gray-800">Logs Categories</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active" aria-current="page">Logs Categories</li>
    </ol>
  </div>

  <div class="row">
    <div class="col-lg-12">
      <div class="card mb-4">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
          <h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-list mr-2"></i>All Logs Categories</h6>
          <button class="btn btn-sm btn-primary" onclick="openAddCategoryModal()">
            <i class="fas fa-plus-circle mr-1"></i> Add Category
          </button>
        </div>
        <div class="table-responsive p-3">
          <table class="table align-items-center table-flush table-hover" id="dataTable">
            <thead class="thead-light">
              <tr>
                <th>#</th>
                <th>Image</th>
                <th>Category Name</th>
                <th>Status</th>
                <th>Created</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($categories as $data):
                $sbadge = $data['status'] == '1' ? 'badge-success' : 'badge-danger';
                $stext  = $data['status'] == '1' ? 'Active' : 'Inactive';
              ?>
              <tr>
                <td><?php echo $i++; ?></td>
                <td>
                  <?php if (!empty($data['category_image'])): ?>
                    <img src="<?php echo htmlspecialchars($data['category_image']); ?>"
                         alt="<?php echo htmlspecialchars($data['category_name']); ?>"
                         class="category-img"
                         onerror="this.src='https://via.placeholder.com/50?text=N/A'">
                  <?php else: ?>
                    <i class="fas fa-image text-muted fa-2x"></i>
                  <?php endif; ?>
                </td>
                <td><strong><?php echo htmlspecialchars($data['category_name']); ?></strong></td>
                <td><span class="badge <?php echo $sbadge; ?>"><?php echo $stext; ?></span></td>
                <td><small><?php echo date('M d, Y', strtotime($data['created_at'])); ?></small></td>
                <td>
                  <div class="btn-group" role="group">
                    <button type="button" class="btn btn-sm btn-primary dropdown-toggle"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                      <i class="fas fa-cog"></i> Actions
                    </button>
                    <div class="dropdown-menu">
                      <a class="dropdown-item" href="#"
                         onclick="openEditCategoryModal(<?php echo $data['id']; ?>, '<?php echo htmlspecialchars($data['category_name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($data['category_image'] ?? '', ENT_QUOTES); ?>', '<?php echo $data['status']; ?>')">
                        <i class="fas fa-edit text-primary"></i> Edit Category
                      </a>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item" href="#"
                         onclick="deleteCategory(<?php echo $data['id']; ?>, '<?php echo htmlspecialchars($data['category_name'], ENT_QUOTES); ?>')">
                        <i class="fas fa-trash text-danger"></i> Delete Category
                      </a>
                    </div>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fas fa-folder-plus mr-2"></i>Add Logs Category</h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label class="font-weight-bold">Category Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control" id="add_cat_name" placeholder="e.g., Facebook, Instagram, TikTok">
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Category Image URL</label>
          <input type="text" class="form-control" id="add_cat_image" placeholder="https://example.com/image.png"
                 oninput="previewCatImage('add_cat_image','add_cat_preview')">
          <small class="text-muted">Enter a direct URL to the category logo/image</small>
          <div class="mt-2 text-center">
            <img id="add_cat_preview" src="" alt="Preview"
                 style="display:none;width:80px;height:80px;object-fit:contain;border:1px solid #e3e6f0;border-radius:8px;padding:4px;">
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" onclick="submitAddCategory()">
          <i class="fas fa-plus-circle mr-1"></i> Add Category
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title"><i class="fas fa-edit mr-2"></i>Edit Logs Category</h5>
        <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="edit_cat_id">
        <div class="form-group">
          <label class="font-weight-bold">Category Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control" id="edit_cat_name">
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Category Image URL</label>
          <input type="text" class="form-control" id="edit_cat_image"
                 oninput="previewCatImage('edit_cat_image','edit_cat_preview')">
          <div class="mt-2 text-center">
            <img id="edit_cat_preview" src="" alt="Preview"
                 style="display:none;width:80px;height:80px;object-fit:contain;border:1px solid #e3e6f0;border-radius:8px;padding:4px;">
          </div>
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Status</label>
          <select class="form-control" id="edit_cat_status">
            <option value="1">Active</option>
            <option value="0">Inactive</option>
          </select>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" onclick="submitEditCategory()">
          <i class="fas fa-save mr-1"></i> Save Changes
        </button>
      </div>
    </div>
  </div>
</div>

<script src="vendor/datatables/jquery.dataTables.min.js"></script>
<script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(document).ready(function() {
  $('#dataTable').DataTable({ ordering: true, pageLength: 25, order: [[4, 'desc']] });
});

function previewCatImage(inputId, previewId) {
  var url = document.getElementById(inputId).value;
  var img = document.getElementById(previewId);
  if (url) { img.src = url; img.style.display = 'inline-block'; }
  else { img.style.display = 'none'; }
}

function openAddCategoryModal() {
  document.getElementById('add_cat_name').value = '';
  document.getElementById('add_cat_image').value = '';
  document.getElementById('add_cat_preview').style.display = 'none';
  $('#addCategoryModal').modal('show');
}

function openEditCategoryModal(id, name, image, status) {
  document.getElementById('edit_cat_id').value = id;
  document.getElementById('edit_cat_name').value = name;
  document.getElementById('edit_cat_image').value = image;
  document.getElementById('edit_cat_status').value = status;
  var prev = document.getElementById('edit_cat_preview');
  if (image) { prev.src = image; prev.style.display = 'inline-block'; }
  else { prev.style.display = 'none'; }
  $('#editCategoryModal').modal('show');
}

function submitAddCategory() {
  var name = document.getElementById('add_cat_name').value.trim();
  if (!name) { Swal.fire('Validation', 'Category name is required.', 'warning'); return; }
  smAjax({ action: 'add_category', category_name: name, category_image: document.getElementById('add_cat_image').value.trim() },
    function() { $('#addCategoryModal').modal('hide'); });
}

function submitEditCategory() {
  var name = document.getElementById('edit_cat_name').value.trim();
  if (!name) { Swal.fire('Validation', 'Category name is required.', 'warning'); return; }
  smAjax({
    action: 'edit_category',
    id: document.getElementById('edit_cat_id').value,
    category_name: name,
    category_image: document.getElementById('edit_cat_image').value.trim(),
    status: document.getElementById('edit_cat_status').value
  }, function() { $('#editCategoryModal').modal('hide'); });
}

function deleteCategory(id, name) {
  Swal.fire({
    title: 'Delete Category?',
    html: `Delete <strong>${name}</strong>? All related services will also be deleted.`,
    icon: 'warning', showCancelButton: true,
    confirmButtonColor: '#e74a3b', cancelButtonColor: '#858796',
    confirmButtonText: 'Yes, Delete', focusCancel: true
  }).then(r => { if (r.isConfirmed) smAjax({ action: 'delete_category', id: id }); });
}

function smAjax(data, onSuccess) {
  Swal.fire({ title: 'Processing...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
  $.ajax({
    url: 'ajax/sm_handler.php', type: 'POST', data: data, dataType: 'json',
    success: function(res) {
      Swal.close();
      if (res.status == '1') {
        Swal.fire({ title: 'Success!', text: res.msg, icon: 'success', confirmButtonColor: '#1cc88a' })
          .then(() => { if (onSuccess) onSuccess(); location.reload(); });
      } else { Swal.fire('Error!', res.msg, 'error'); }
    },
    error: function() { Swal.close(); Swal.fire('Error!', 'An error occurred. Please try again.', 'error'); }
  });
}
</script>

<?php include('include/footer.php'); ?>