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

try {
    $stmt = $pdo->query("
        SELECT s.*, c.category_name, c.category_image
        FROM sm_services s
        LEFT JOIN sm_categories c ON s.category_id = c.id
        ORDER BY s.id DESC
    ");
    $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $services = [];
    error_log("Logs Services fetch error: " . $e->getMessage());
}

// Fetch active categories for the add/edit dropdowns
try {
    $cat_stmt = $pdo->query("SELECT id, category_name FROM sm_categories WHERE status='1' ORDER BY category_name ASC");
    $categories = $cat_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $categories = [];
}
?>
<title>Logs Services - <?php echo $site_data['web_name']; ?></title>

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

<style>
  .service-img { width: 40px; height: 40px; object-fit: contain; border: 1px solid #e3e6f0; border-radius: 6px; padding: 2px; background: white; }
  .service-desc { max-width: 250px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .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 Services</h1>
    <ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="dashboard.php">Home</a></li>
      <li class="breadcrumb-item active" aria-current="page">Logs Services</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 Services</h6>
          <button class="btn btn-sm btn-primary" onclick="openAddServiceModal()">
            <i class="fas fa-plus-circle mr-1"></i> Add Service
          </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>Category</th>
                <th>Service Name</th>
                <th>Description</th>
                <th>Amount</th>
                <th>Status</th>
                <th>Preview</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php $i = 1; foreach ($services as $data):
                switch ($data['status']) {
                  case 'available': $sbadge = 'badge-success';   $stext = 'Available'; break;
                  case 'sold':      $sbadge = 'badge-danger';    $stext = 'Sold';      break;
                  case 'pending':   $sbadge = 'badge-warning';   $stext = 'Pending';   break;
                  default:          $sbadge = 'badge-secondary'; $stext = ucfirst($data['status']);
                }
              ?>
              <tr>
                <td><?php echo $i++; ?></td>
                <td>
                  <div class="d-flex align-items-center">
                    <?php if (!empty($data['category_image'])): ?>
                      <img src="<?php echo htmlspecialchars($data['category_image']); ?>"
                           alt="<?php echo htmlspecialchars($data['category_name']); ?>"
                           class="service-img mr-2"
                           onerror="this.style.display='none'">
                    <?php endif; ?>
                    <span><?php echo htmlspecialchars($data['category_name'] ?? '—'); ?></span>
                  </div>
                </td>
                <td><strong><?php echo htmlspecialchars($data['service_name']); ?></strong></td>
                <td>
                  <div class="service-desc" title="<?php echo htmlspecialchars($data['service_description']); ?>">
                    <?php echo htmlspecialchars($data['service_description']); ?>
                  </div>
                </td>
                <td><strong>NGN<?php echo number_format($data['amount'], 2); ?></strong></td>
                <td><span class="badge <?php echo $sbadge; ?>"><?php echo $stext; ?></span></td>
                <td>
                  <?php if (!empty($data['preview_link'])): ?>
                    <a href="<?php echo htmlspecialchars($data['preview_link']); ?>" target="_blank" class="btn btn-sm btn-info">
                      <i class="fas fa-external-link-alt"></i>
                    </a>
                  <?php else: ?>
                    <span class="text-muted">—</span>
                  <?php endif; ?>
                </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="openEditServiceModal(
                           <?php echo $data['id']; ?>,
                           <?php echo $data['category_id']; ?>,
                           '<?php echo htmlspecialchars($data['service_name'], ENT_QUOTES); ?>',
                           '<?php echo htmlspecialchars($data['service_description'], ENT_QUOTES); ?>',
                           '<?php echo $data['amount']; ?>',
                           '<?php echo htmlspecialchars($data['preview_link'] ?? '', ENT_QUOTES); ?>',
                           '<?php echo htmlspecialchars($data['login_credentials'] ?? '', ENT_QUOTES); ?>',
                           '<?php echo $data['status']; ?>'
                         )">
                        <i class="fas fa-edit text-primary"></i> Edit Service
                      </a>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item" href="#"
                         onclick="deleteService(<?php echo $data['id']; ?>, '<?php echo htmlspecialchars($data['service_name'], ENT_QUOTES); ?>')">
                        <i class="fas fa-trash text-danger"></i> Delete Service
                      </a>
                    </div>
                  </div>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Category options for JS -->
<script>
const categoryOptions = [
  <?php foreach ($categories as $c): ?>
  { id: <?php echo $c['id']; ?>, name: "<?php echo htmlspecialchars($c['category_name'], ENT_QUOTES); ?>" },
  <?php endforeach; ?>
];
function buildCategoryOptions(selectedId) {
  return categoryOptions.map(c =>
    `<option value="${c.id}" ${c.id == selectedId ? 'selected' : ''}>${c.name}</option>`
  ).join('');
}
</script>

<!-- Add Service Modal -->
<div class="modal fade" id="addServiceModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg 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-plus-square mr-2"></i>Add Logs Service</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 <span class="text-danger">*</span></label>
          <select class="form-control" id="add_svc_category"></select>
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Service Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control" id="add_svc_name" placeholder="e.g., Premium Facebook Account">
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Description <span class="text-danger">*</span></label>
          <textarea class="form-control" id="add_svc_desc" rows="3" placeholder="Enter detailed description..."></textarea>
        </div>
        <div class="row">
          <div class="col-md-6">
            <div class="form-group">
              <label class="font-weight-bold">Amount NGN <span class="text-danger">*</span></label>
              <input type="number" step="0.01" class="form-control" id="add_svc_amount" placeholder="0.00">
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label class="font-weight-bold">Preview Link (Optional)</label>
              <input type="url" class="form-control" id="add_svc_preview" placeholder="https://...">
            </div>
          </div>
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Login Credentials <span class="text-danger">*</span></label>
          <textarea class="form-control" id="add_svc_credentials" rows="4"
                    placeholder="Email: example@email.com&#10;Password: your_password"></textarea>
          <small class="text-muted"><i class="fas fa-lock mr-1"></i>Shown to buyer after purchase</small>
        </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="submitAddService()">
          <i class="fas fa-plus-circle mr-1"></i> Add Service
        </button>
      </div>
    </div>
  </div>
</div>

<!-- Edit Service Modal -->
<div class="modal fade" id="editServiceModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg 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 Service</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_svc_id">
        <div class="form-group">
          <label class="font-weight-bold">Category <span class="text-danger">*</span></label>
          <select class="form-control" id="edit_svc_category"></select>
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Service Name <span class="text-danger">*</span></label>
          <input type="text" class="form-control" id="edit_svc_name">
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Description <span class="text-danger">*</span></label>
          <textarea class="form-control" id="edit_svc_desc" rows="3"></textarea>
        </div>
        <div class="row">
          <div class="col-md-4">
            <div class="form-group">
              <label class="font-weight-bold">Amount (NGN) <span class="text-danger">*</span></label>
              <input type="number" step="0.01" class="form-control" id="edit_svc_amount">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label class="font-weight-bold">Preview Link</label>
              <input type="url" class="form-control" id="edit_svc_preview" placeholder="https://...">
            </div>
          </div>
          <div class="col-md-4">
            <div class="form-group">
              <label class="font-weight-bold">Status</label>
              <select class="form-control" id="edit_svc_status">
                <option value="available">Available</option>
                <option value="sold">Sold</option>
                <option value="pending">Pending</option>
              </select>
            </div>
          </div>
        </div>
        <div class="form-group">
          <label class="font-weight-bold">Login Credentials</label>
          <textarea class="form-control" id="edit_svc_credentials" rows="4"></textarea>
          <small class="text-muted"><i class="fas fa-lock mr-1"></i>Shown to buyer after purchase</small>
        </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="submitEditService()">
          <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: [[0, 'desc']] });
});

function openAddServiceModal() {
  ['add_svc_name','add_svc_desc','add_svc_amount','add_svc_preview','add_svc_credentials'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('add_svc_category').innerHTML = '<option value="">-- Select Category --</option>' + buildCategoryOptions(null);
  $('#addServiceModal').modal('show');
}

function openEditServiceModal(id, catId, name, desc, amount, preview, credentials, status) {
  document.getElementById('edit_svc_id').value          = id;
  document.getElementById('edit_svc_name').value        = name;
  document.getElementById('edit_svc_desc').value        = desc;
  document.getElementById('edit_svc_amount').value      = amount;
  document.getElementById('edit_svc_preview').value     = preview;
  document.getElementById('edit_svc_credentials').value = credentials;
  document.getElementById('edit_svc_status').value      = status;
  document.getElementById('edit_svc_category').innerHTML = buildCategoryOptions(catId);
  $('#editServiceModal').modal('show');
}

function submitAddService() {
  var cat  = document.getElementById('add_svc_category').value;
  var name = document.getElementById('add_svc_name').value.trim();
  var desc = document.getElementById('add_svc_desc').value.trim();
  var amt  = document.getElementById('add_svc_amount').value;
  var cred = document.getElementById('add_svc_credentials').value.trim();
  if (!cat || !name || !desc || !amt || !cred) {
    Swal.fire('Validation', 'Please fill in all required fields.', 'warning'); return;
  }
  smAjax({
    action: 'add_service', category_id: cat, service_name: name, service_description: desc,
    amount: amt, preview_link: document.getElementById('add_svc_preview').value.trim(),
    login_credentials: cred
  }, function() { $('#addServiceModal').modal('hide'); });
}

function submitEditService() {
  var name = document.getElementById('edit_svc_name').value.trim();
  var amt  = document.getElementById('edit_svc_amount').value;
  if (!name || !amt) { Swal.fire('Validation', 'Name and amount are required.', 'warning'); return; }
  smAjax({
    action: 'edit_service',
    id:                    document.getElementById('edit_svc_id').value,
    category_id:           document.getElementById('edit_svc_category').value,
    service_name:          name,
    service_description:   document.getElementById('edit_svc_desc').value.trim(),
    amount:                amt,
    preview_link:          document.getElementById('edit_svc_preview').value.trim(),
    login_credentials:     document.getElementById('edit_svc_credentials').value.trim(),
    status:                document.getElementById('edit_svc_status').value
  }, function() { $('#editServiceModal').modal('hide'); });
}

function deleteService(id, name) {
  Swal.fire({
    title: 'Delete Service?',
    html: `Permanently delete <strong>${name}</strong>?`,
    icon: 'warning', showCancelButton: true,
    confirmButtonColor: '#e74a3b', cancelButtonColor: '#858796',
    confirmButtonText: 'Yes, Delete', focusCancel: true
  }).then(r => { if (r.isConfirmed) smAjax({ action: 'delete_service', 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'); ?>