<?php
require_once __DIR__ . '/../../Config/functions.php';
require_login();
include __DIR__ . '/../layouts/header.php';
include __DIR__ . '/../layouts/sidebar.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Customers | SGAccount</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables.net-bs4@1.13.4/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="assets/css/custom.css">
</head>
<!-- ============================================================= -->
<!-- 🏢 COMPANY SETTINGS PAGE -->
<!-- ============================================================= -->
<div class="content-wrapper p-3">

  <!-- Page Header -->
  <section class="content-header d-flex justify-content-between align-items-center">
    <h1 class="mb-0"><i class="fas fa-building mr-2"></i> Company Settings</h1>
    <button class="btn btn-primary" data-toggle="modal" data-target="#addModal">
      <i class="fas fa-plus-circle"></i> Add Company
    </button>
  </section>

  <!-- Main Content -->
  <section class="content mt-3">
    <div class="card shadow-sm">
      <div class="card-header bg-primary text-white">
        <h3 class="card-title mb-0"><i class="fas fa-list mr-2"></i> Company List</h3>
      </div>
      <div class="card-body">
        <table id="companyTable" class="table table-bordered table-hover table-striped">
          <thead class="thead-light">
            <tr>
              <th style="width:60px;">ID</th>
              <th>Name</th>
              <th>Phone</th>
              <th>Email</th>
              <th>GST No</th>
              <th>Logo</th>
              <th style="width:160px;">Action</th>
            </tr>
          </thead>
          <tbody>
            <?php if (!empty($companies)): ?>
              <?php foreach ($companies as $c): ?>
              <tr>
                <td><?= $c['id'] ?></td>
                <td><?= htmlspecialchars($c['name']) ?></td>
                <td><?= htmlspecialchars($c['phone']) ?></td>
                <td><?= htmlspecialchars($c['email'] ?? '-') ?></td>
                <td><?= htmlspecialchars($c['gst_no'] ?? '-') ?></td>
                <td>
                  <?php if (!empty($c['logo_path'])): ?>
                    <img src="/uploads/<?= htmlspecialchars($c['logo_path']) ?>"
                         class="img-thumbnail" width="60" height="60">
                  <?php else: ?>
                    <span class="text-muted">No Logo</span>
                  <?php endif; ?>
                </td>
                <td>
                  <a href="router.php?page=company-view&id=<?= $c['id'] ?>" 
                     class="btn btn-sm btn-secondary" title="View">
                    <i class="fas fa-eye"></i>
                  </a>
                  <button class="btn btn-sm btn-info editBtn" data-id="<?= $c['id'] ?>" title="Edit">
                    <i class="fas fa-edit"></i>
                  </button>
                  <button class="btn btn-sm btn-danger deleteBtn" data-id="<?= $c['id'] ?>" title="Delete">
                    <i class="fas fa-trash"></i>
                  </button>
                </td>
              </tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr><td colspan="7" class="text-center text-muted">No company records found.</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </section>
</div>

<!-- Include Modals -->
<?php include __DIR__ . '/modal-add.php'; ?>
<?php include __DIR__ . '/modal-edit.php'; ?>

<?php include __DIR__ . '/../layouts/footer.php'; ?>

<!-- ============================================================= -->
<!-- ⚙️ SCRIPTS -->
<!-- ============================================================= -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>

<script>
$(document).ready(function() {

  // Initialize DataTable
  $('#companyTable').DataTable({
    pageLength: 10,
    ordering: true,
    responsive: true,
    language: {
      search: "_INPUT_",
      searchPlaceholder: "Search company..."
    }
  });

  // ===========================================================
  // 🧩 ADD COMPANY
  // ===========================================================
  $('#addForm').submit(function(e){
    e.preventDefault();
    const formData = new FormData(this);

    $.ajax({
      url: '/ajax/company/add.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res){
        Swal.fire({
          icon: 'success',
          title: 'Added!',
          text: res,
          timer: 2000,
          showConfirmButton: false
        }).then(()=> location.reload());
      },
      error: function(){
        Swal.fire('Error', 'Failed to add company. Please try again.', 'error');
      }
    });
  });

  // ===========================================================
  // ✏️ EDIT COMPANY - LOAD DATA
  // ===========================================================
  $('.editBtn').click(function(){
    const id = $(this).data('id');
    $.get('/ajax/company/edit.php', {id:id}, function(res){
      const data = JSON.parse(res);
      $('#edit_id').val(data.id);
      $('#edit_name').val(data.name);
      $('#edit_registration_no').val(data.registration_no);
      $('#edit_address').val(data.address);
      $('#edit_phone').val(data.phone);
      $('#edit_email').val(data.email);
      $('#edit_gst_no').val(data.gst_no);
      $('#editModal').modal('show');
    }).fail(function(){
      Swal.fire('Error', 'Unable to fetch company data.', 'error');
    });
  });

  // ===========================================================
  // 💾 UPDATE COMPANY
  // ===========================================================
  $('#editForm').submit(function(e){
    e.preventDefault();
    const formData = new FormData(this);

    $.ajax({
      url: '/ajax/company/edit.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(res){
        Swal.fire({
          icon: 'success',
          title: 'Updated!',
          text: res,
          timer: 2000,
          showConfirmButton: false
        }).then(()=> location.reload());
      },
      error: function(){
        Swal.fire('Error', 'Update failed. Please try again.', 'error');
      }
    });
  });

  // ===========================================================
  // 🗑️ DELETE COMPANY
  // ===========================================================
  $('.deleteBtn').click(function(){
    const id = $(this).data('id');

    Swal.fire({
      title: 'Are you sure?',
      text: 'This will permanently delete the company record!',
      icon: 'warning',
      showCancelButton: true,
      confirmButtonText: 'Yes, delete it!',
      cancelButtonText: 'Cancel'
    }).then(result => {
      if(result.isConfirmed){
        $.post('/ajax/company/delete.php', {id:id}, function(res){
          Swal.fire({
            icon: 'success',
            title: 'Deleted!',
            text: res,
            timer: 2000,
            showConfirmButton: false
          }).then(()=> location.reload());
        }).fail(function(){
          Swal.fire('Error', 'Delete failed.', 'error');
        });
      }
    });
  });
});
</script>
