<?php
// ===== Inline AJAX endpoint for fetching inventory rows =====
// Do this BEFORE output to avoid mixing JSON with HTML.
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);

if (isset($_GET['ajax']) && $_GET['ajax'] === 'inventory') {
  require_once __DIR__ . '/../config.php';
  header('Content-Type: application/json; charset=utf-8');

  $uid = isset($_GET['uid']) ? (int)$_GET['uid'] : 0;
  if ($uid <= 0) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'message' => 'Invalid unit id.']);
    exit;
  }

  $items = [];
  if ($res = $link->prepare("SELECT item_name, item_quantity FROM units_inventory WHERE uid = ? ORDER BY item_name ASC")) {
    $res->bind_param('i', $uid);
    if ($res->execute()) {
      $rows = $res->get_result();
      while ($r = $rows->fetch_assoc()) {
        $items[] = [
          'item_name'     => $r['item_name'],
          'item_quantity' => (int)$r['item_quantity']
        ];
      }
    }
    $res->close();
  }

  echo json_encode(['ok' => true, 'items' => $items]);
  exit;
}
// ===== End inline AJAX endpoint =====

include_once('../header.php');
if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}

include_once(ROOT_PATH . 'language/' . $lang_code_global . '/lang_unit_list.php');

$delinfo = 'none';
$addinfo = 'none';
$msg = "";

// Handle delete (safe int)
if (isset($_GET['id']) && $_GET['id'] !== '' && (int)$_GET['id'] > 0) {
  $uid = (int)$_GET['id'];
  mysqli_query($link, "DELETE FROM `units` WHERE uid = {$uid}");
  $delinfo = 'block';
}

// Flash messages
if (isset($_GET['m']) && $_GET['m'] == 'add') {
  $addinfo = 'block';
  $msg = $_data['add_unit_successfully'];
} elseif (isset($_GET['m']) && $_GET['m'] == 'up') {
  $addinfo = 'block';
  $msg = $_data['update_unit_successfully'];
}

function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

// Fetch blocks for filter
$blocks = [];
$qBlocks = mysqli_query($link, "SELECT bid, b_name FROM blocks ORDER BY b_name ASC");
while ($b = mysqli_fetch_assoc($qBlocks)) { $blocks[] = $b; }

// Fetch units (with inventory count)
$rows = [];
$sql = "
  SELECT u.*, f.b_name,
         IFNULL(inv.cnt, 0) AS inv_count
  FROM unit_view u
  INNER JOIN blocks f ON f.bid = u.bid
  LEFT JOIN (
    SELECT uid, COUNT(*) AS cnt
    FROM units_inventory
    GROUP BY uid
  ) inv ON inv.uid = u.uid
  ORDER BY u.bid ASC, u.unit_no ASC
";
$result = mysqli_query($link, $sql);
while ($r = mysqli_fetch_assoc($result)) { $rows[] = $r; }
?>
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <i class="fa fa-building"></i> <?= e($_data['unit_list_title']); ?>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL ?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']); ?></a></li>
    <li class="active"><?= e($_data['add_new_unit_information_breadcam']); ?></li>
    <li class="active"><?= e($_data['unit_list_title']); ?></li>
  </ol>
</section>

<!-- Friendly styles & fonts -->
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{
    --ink:#0f172a; --ink-2:#334155; --muted:#64748b; --line:#e5e7eb;
    --brand:#2563eb; --ok:#16a34a; --warn:#d97706; --danger:#dc2626;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff;
  }
  .content-wrapper, .box, .table, label, .btn, .alert, input, select {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial;
    color:var(--ink-2);
  }
  .content-header > h1{ font-weight:800; color:var(--ink); letter-spacing:.2px; }

  /* Card shell */
  .box.box-success{
    border-radius:16px; overflow:hidden; border:1px solid var(--line);
    box-shadow:0 12px 32px rgba(2,6,23,.08);
    background:var(--card);
  }
  .box .box-header{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
    display:flex; align-items:center; justify-content:space-between; gap:10px;
    padding:10px 14px;
  }
  .box .box-title{ font-weight:800; color:var(--ink); margin:0; font-size:16px; }

  /* Inline toolbar (smaller buttons) */
  .toolbar{ display:flex; align-items:center; gap:6px; flex-wrap:wrap; }
  .btn, .btn:focus { outline: none; }
  .btn { border-radius:10px; border:1px solid var(--line); background:#fff; color:var(--ink-2); font-weight:700; }
  .btn i { margin-right:6px; }
  .btn:hover { background:#f8fafc; }
  .btn-slim{ padding:6px 10px; font-size:12px; line-height:1.2; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary:hover{ background:#1d4ed8; }
  .btn-success-solid{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-success-solid:hover{ background:#15803d; }

  .input, .select{
    border:1px solid var(--line); background:#fff; border-radius:10px; padding:6px 10px; outline:none; font-weight:600; font-size:12px;
    height:32px;
  }
  .input:focus, .select:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

  /* Polished table */
  .table.sakotable{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table > thead > tr > th{
    border-bottom:1px solid var(--line) !important;
    color:var(--ink); font-weight:800; text-transform:uppercase; font-size:12px; letter-spacing:.3px;
    background:#fff;
  }
  .table > tbody > tr { background:#fff; border:1px solid var(--line); }
  .table > tbody > tr > td{ vertical-align:middle; padding:10px; font-size:13px; }
  .table > tbody > tr > td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .table > tbody > tr > td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }
  .table > tbody > tr:hover { background:#fafafa; }

  .chip{
    display:inline-flex; align-items:center; gap:6px; padding:4px 8px; border-radius:999px;
    font-size:11px; font-weight:700; border:1px solid var(--line);
  }
  .chip.gray{ background:#fff; color:#6b7280; }
  .chip.green{ background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }

  .alert{ border-radius:12px; border:none; box-shadow:0 8px 24px rgba(0,0,0,.08); }
  .alert-success{ background:#ecfdf5; color:#065f46; }
  .alert-danger{ background:#fef2f2; color:#7f1d1d; }

  /* Smaller row action buttons */
  .btn-row{ padding:4px 8px; font-size:12px; line-height:1.2; border-radius:10px; border:1px solid var(--line); }
  .btn-row i{ margin-right:0; font-size:12px; }
  .btn-row + .btn-row{ margin-left:6px; }
  .btn-warning-solid{ background:#f59e0b; border-color:#f59e0b; color:#fff; }
  .btn-warning-solid:hover{ background:#d97706; }
  .btn-danger-solid{ background:var(--danger); border-color:var(--danger); color:#fff; }
  .btn-danger-solid:hover{ filter:brightness(0.95); }
  .btn-primary-solid{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary-solid:hover{ background:#1d4ed8; }

  /* Modal */
  .modal-content{ border-radius:16px; overflow:hidden; }
  .modal-header.green_header{
    background:linear-gradient(135deg,var(--soft),var(--soft2));
    border-bottom:1px solid var(--line);
  }
  .modal-title{ font-weight:800; color:var(--ink); font-size:16px; }
  #inventoryTable thead th{ font-weight:800; font-size:12px; }
  #inventoryTable .qty { max-width: 110px; }

  /* Compact modal buttons */
  .btn-compact{ padding:6px 10px !important; font-size:12px !important; line-height:1.2 !important; border-radius:10px !important; }
  .btn-compact i{ font-size:12px; margin-right:4px; }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12">

      <!-- Alerts -->
      <div id="me" class="alert alert-danger alert-dismissable" style="display:<?= $delinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4><i class="icon fa fa-ban"></i> <?= e($_data['delete_text']); ?>!</h4>
        <?= e($_data['delete_unit_information']); ?>
      </div>
      <div id="you" class="alert alert-success alert-dismissable" style="display:<?= $addinfo; ?>">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button"><i class="fa fa-close"></i></button>
        <h4><i class="icon fa fa-check"></i> <?= e($_data['success']); ?>!</h4>
        <?= e($msg); ?>
      </div>

      <div class="box box-success">
        <div class="box-header">
          <h3 class="box-title"><?= e($_data['unit_list_title']); ?></h3>

          <!-- Single-line toolbar: actions + filters + search (now slimmer) -->
          <div class="toolbar">
            <a class="btn btn-success-solid btn-slim" href="<?= WEB_URL; ?>unit/addunit.php" data-toggle="tooltip" title="<?= e($_data['add_unit']); ?>">
              <i class="fa fa-plus"></i><?= e($_data['add_unit']); ?>
            </a>
            <a class="btn btn-primary btn-slim" href="<?= WEB_URL; ?>dashboard.php" data-toggle="tooltip" title="<?= e($_data['home_breadcam']); ?>">
              <i class="fa fa-dashboard"></i><?= e($_data['home_breadcam']); ?>
            </a>

            <select id="blockFilter" class="select"><option value="">All Blocks</option>
              <?php foreach ($blocks as $b): ?>
                <option value="<?= e($b['b_name']); ?>"><?= e($b['b_name']); ?></option>
              <?php endforeach; ?>
            </select>

            <select id="invFilter" class="select">
              <option value="">Inventory: All</option>
              <option value="taken">Inventory Taken</option>
              <option value="not">Not Taken</option>
            </select>

            <input id="unitSearch" class="input" placeholder="Search units…">
          </div>
        </div>

        <div class="box-body">
          <div class="table-responsive">
            <table id="unitTable" class="table sakotable table-bordered table-striped">
              <thead>
                <tr>
                  <th><?= e($_data['b_name']); ?></th>
                  <th><?= e($_data['unit_no']); ?></th>
                  <th>Floor</th>
                  <th>Daily Rate</th>
                  <th>Monthly Rate</th>
                  <th>Inventory</th>
                  <th><?= e($_data['action_text']); ?></th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($rows as $row):
                  $invCount = (int)$row['inv_count'];
                  $chip = $invCount > 0
                          ? '<span class="chip green"><i class="fa fa-check-circle"></i> Taken ('.(int)$invCount.')</span>'
                          : '<span class="chip gray"><i class="fa fa-info-circle"></i> Inventory not taken yet</span>';
                ?>
                <tr data-block="<?= e($row['b_name']); ?>" data-inv="<?= $invCount > 0 ? 'taken' : 'not'; ?>">
                  <td><?= e($row['b_name']); ?></td>
                  <td><?= e($row['unit_no']); ?></td>
                  <td><?= e($row['floor']); ?></td>
                  <td><?= e($row['rate_currency']) . " " . number_format((float)$row['d_rate'], 2); ?></td>
                  <td><?= e($row['rate_currency']) . " " . number_format((float)$row['rate'], 2); ?></td>
                  <td><?= $chip; ?></td>
                  <td>
                    <a class="btn btn-warning-solid btn-row" href="<?= WEB_URL; ?>unit/addunit.php?id=<?= (int)$row['uid']; ?>" data-toggle="tooltip" title="<?= e($_data['edit_text']); ?>">
                      <i class="fa fa-pencil"></i>
                    </a>
                    <a class="btn btn-primary-solid btn-row" href="javascript:;" data-toggle="tooltip" title="Edit/Take Inventory"
                       onclick="openInventoryModal(<?= (int)$row['uid']; ?>, '<?= e($row['unit_no']); ?>', '<?= e($row['b_name']); ?>');">
                      <i class="fa fa-clipboard"></i>
                    </a>
                    <a class="btn btn-danger-solid btn-row" href="javascript:;" data-toggle="tooltip" title="<?= e($_data['delete_text']); ?>"
                       onclick="deleteUnit(<?= (int)$row['uid']; ?>);">
                      <i class="fa fa-trash-o"></i>
                    </a>
                  </td>
                </tr>
                <?php endforeach; mysqli_close($link); $link = NULL; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>

  <!-- Inventory Modal -->
  <div id="inventoryModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="inventoryModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header green_header">
          <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true"><i class="fa fa-close"></i></span></button>
          <h3 class="modal-title"><i class="fa fa-clipboard"></i> Inventory for <span id="unitLabel"></span></h3>
        </div>
        <div class="modal-body">
          <div id="invHint" class="alert alert-info" style="display:none; margin-bottom:12px;">
            No inventory recorded for this unit yet. Add items below to get started.
          </div>

          <table id="inventoryTable" class="table table-bordered">
            <thead>
              <tr>
                <th style="width:55%;">Item Name</th>
                <th style="width:20%;">Quantity</th>
                <th style="width:25%;">Action</th>
              </tr>
            </thead>
            <tbody></tbody>
          </table>

          <div class="text-right" style="display:flex;gap:8px;justify-content:flex-end;">
            <button id="addRow" class="btn btn-success-solid btn-compact"><i class="fa fa-plus"></i> Add Row</button>
            <button id="clearAll" class="btn btn-danger-solid btn-compact"><i class="fa fa-trash"></i> Clear All</button>
          </div>
        </div>
        <div class="modal-footer" style="display:flex;gap:8px;justify-content:flex-end;">
          <button type="button" class="btn btn-primary btn-compact" id="saveInventory"><i class="fa fa-save"></i> Save Changes</button>
        </div>
      </div>
    </div>
  </div>
</section>

<script>
  let unitId = 0;

  function deleteUnit(Id){
    const go = function(){ window.location = '<?= WEB_URL; ?>unit/unitlist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') sweetConfirmDelete(go);
    else if (confirm("<?= addslashes($_data['confirm'] ?? 'Are you sure?'); ?>")) go();
  }

  function openInventoryModal(id, unitNo, bName) {
    unitId = id;
    $("#unitLabel").text(`${unitNo} (${bName})`);
    $("#inventoryTable tbody").empty();
    $("#invHint").hide();

    $.getJSON("<?= WEB_URL ?>unit/unitlist.php", { ajax: 'inventory', uid: unitId })
      .done(function(resp) {
        if (resp && resp.ok && Array.isArray(resp.items) && resp.items.length) {
          resp.items.forEach(function(it){ appendRow(it.item_name, it.item_quantity); });
        } else {
          $("#invHint").show();
          appendRow('', 1);
        }
        $("#inventoryModal").modal('show');
      })
      .fail(function(){ alert("Failed to load inventory for this unit."); });
  }

  function appendRow(name, qty){
    const safeName = name ? $('<div/>').text(name).html() : '';
    const safeQty  = qty && !isNaN(qty) ? parseInt(qty,10) : 1;

    $("#inventoryTable tbody").append(`
      <tr>
        <td><input type="text" class="form-control" name="item_name[]" value="${safeName}" placeholder="e.g., Ceiling fan, Light bulb, Shelf"></td>
        <td style="max-width:120px;"><input type="number" class="form-control qty" name="item_quantity[]" min="1" value="${safeQty}"></td>
        <td><button class="btn btn-danger-solid btn-compact removeRow"><i class="fa fa-trash"></i> Remove</button></td>
      </tr>
    `);
  }

  $(document).on("click", ".removeRow", function(){
    $(this).closest("tr").remove();
    if ($("#inventoryTable tbody tr").length === 0) {
      $("#invHint").show();
      appendRow('', 1);
    }
  });

  $("#addRow").on('click', function(){ appendRow('', 1); });

  $("#clearAll").on('click', function(){
    if (confirm("Clear all rows? This will remove all current entries in the editor (not yet saved).")) {
      $("#inventoryTable tbody").empty();
      $("#invHint").show();
      appendRow('', 1);
    }
  });

  $("#saveInventory").click(function(){
    let inventoryData = [];
    $("#inventoryTable tbody tr").each(function() {
      const itemName = $(this).find("input[name='item_name[]']").val().trim();
      const qtyVal   = parseInt($(this).find("input[name='item_quantity[]']").val(), 10);
      if (itemName && qtyVal > 0) inventoryData.push({ item_name: itemName, item_quantity: qtyVal });
    });

    if (inventoryData.length === 0) {
      alert("Please add at least one valid inventory item.");
      return;
    }

    $.ajax({
      url: "<?= WEB_URL ?>unit/unitinventory.php",
      method: "POST",
      data: { uid: unitId, inventory: inventoryData },
      success: function(response) {
        try {
          const r = typeof response === 'string' ? JSON.parse(response) : response;
          alert((r && r.message) ? r.message : "Inventory saved successfully!");
        } catch(_) {
          alert("Inventory saved successfully!");
        }
        $("#inventoryModal").modal('hide');
        location.reload();
      },
      error: function(){ alert("An error occurred while saving the inventory."); }
    });
  });

  // Simple client-side filters & search (works even without DataTables)
  function applyFilters(){
    const q        = ($("#unitSearch").val() || '').toLowerCase().trim();
    const blockSel = $("#blockFilter").val();
    const invSel   = $("#invFilter").val(); // '', 'taken', 'not'

    $("#unitTable tbody tr").each(function(){
      const $tr = $(this);
      const text = $tr.text().toLowerCase();
      const blk  = $tr.data('block');
      const inv  = $tr.data('inv'); // 'taken' | 'not'

      let show = true;
      if (q && text.indexOf(q) === -1) show = false;
      if (blockSel && blk !== blockSel) show = false;
      if (invSel && inv !== invSel) show = false;

      $tr.toggle(show);
    });
  }

  $("#unitSearch").on('keyup input', applyFilters);
  $("#blockFilter, #invFilter").on('change', applyFilters);

  // Auto-hide alerts
  $(function(){
    setTimeout(function(){ $("#me, #you").fadeOut(300); }, 3000);
  });
</script>

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