<?php
include_once('../header.php');
if(!check_login()){
  header("Location: " . WEB_URL . "logout.php");
  exit();
}
include_once(ROOT_PATH.'language/'.$lang_code_global.'/lang_tenant_list.php');

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

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

/* Delete */
if (isset($_GET['id']) && (int)$_GET['id'] > 0){
  $bbid = (int)$_GET['id'];
  mysqli_query($link, "DELETE FROM `buyers` WHERE bbid = {$bbid}");
  $delinfo = 'block';
}

/* Flash */
if (isset($_GET['m']) && $_GET['m'] == 'add'){ $addinfo = 'block'; $msg = $_data['added_buyer_successfully']; }
if (isset($_GET['m']) && $_GET['m'] == 'up'){  $addinfo = 'block'; $msg = $_data['update_buyer_successfully']; }
if (isset($_SESSION["message"])) { $addinfo = 'block'; $msg = $_SESSION["message"]; unset($_SESSION["message"]); }

$assign_unit_url = WEB_URL . "buyer/addbuyer.php?action=assign";
?>
<section class="content-header" style="margin-bottom:8px;">
  <h1 style="display:flex;align-items:center;gap:10px;margin:0;">
    <span style="display:inline-flex;width:38px;height:38px;border-radius:12px;background:#2563eb15;align-items:center;justify-content:center;">
      <i class="fa fa-address-book" style="color:#1e40af;"></i>
    </span>
    <span><?= e($_data['buyer_list']); ?></span>
  </h1>
  <ol class="breadcrumb" style="margin-top:8px;">
    <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_buyer_information_breadcam']); ?></li>
    <li class="active"><?= e($_data['buyer_list']); ?></li>
  </ol>
</section>

<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap" rel="stylesheet">
<style>
  :root{ color-scheme:light dark; --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff; --shadow:0 14px 40px rgba(2,6,23,.10);
    --brand:#2563eb; --ok:#16a34a; --danger:#dc2626; --row:#f9fafb; }
  @media (prefers-color-scheme: dark){
    :root{ --ink:#e5e7eb; --ink2:#cbd5e1; --muted:#94a3b8; --line:#1f2a38; --soft:#0b1220; --soft2:#0f172a;
      --card:#0b1220; --shadow:0 10px 30px rgba(0,0,0,.35); --row:#0f172a; }
  }
  .content-wrapper, .box, .table, label, .btn, .alert, input, select, body {
    font-family:'Inter',system-ui,Segoe UI,Roboto,Helvetica,Arial; color:var(--ink2);
  }
  .page-card{ border:1px solid var(--line); border-radius:18px; overflow:hidden; background:var(--card); box-shadow:var(--shadow); }
  .page-head{ background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line);
    padding:12px; display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap; }
  .page-title{ margin:0; font-weight:800; color:var(--ink); display:flex; align-items:center; gap:8px; }
  .toolbar{ display:flex; align-items:center; gap:8px; flex-wrap:wrap; }

  .btn{ border-radius:10px; font-weight:700; border:1px solid var(--line); }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-danger{ background:var(--danger); border-color:var(--danger); color:#fff; }
  .btn-ghost{ background:transparent; color:var(--ink2); }
  .btn-ghost:hover{ background:rgba(148,163,184,.12); }

  .input{ border:1px solid var(--line); background:transparent; color:var(--ink2); border-radius:10px; padding:6px 10px; height:34px; font-weight:600; font-size:12px; }
  .input:focus{ border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.12); }
  .kbd{ font-family:ui-monospace,Consolas,monospace; padding:2px 6px; border:1px solid var(--line); border-radius:6px; font-size:11px; }

  /* We use .buyerTable instead of .sakotable to avoid any global auto-init scripts */
  .table-wrap{ width:100%; overflow:auto; }
  table.buyerTable{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .buyerTable thead th{
    position:sticky; top:0; z-index:1; background:var(--card) !important;
    border-bottom:1px solid var(--line) !important; color:var(--ink); font-weight:800; font-size:11px;
    text-transform:uppercase; letter-spacing:.3px;
  }
  .buyerTable tbody tr td{
    vertical-align:middle; padding:10px; font-size:13px; background:var(--card);
    border-top:1px solid var(--line); border-bottom:1px solid var(--line);
  }
  .buyerTable tbody tr td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .buyerTable tbody tr td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }
  .buyerTable tbody tr:hover td{ background:var(--row); transition:background .15s ease; }

  .avatar{ width:46px; height:46px; border-radius:12px; object-fit:cover; border:1px solid var(--line); }
  .alert{ border-radius:12px; border:none; box-shadow:var(--shadow); }
  .alert-success{ background:rgba(187,247,208,.35); color:#064e3b; }
  .alert-danger{ background:rgba(254,202,202,.38); color:#7f1d1d; }
  .modal.sd .modal-content{ border-radius:16px; overflow:hidden; box-shadow:0 24px 60px rgba(2,6,23,.20); }
  .modal.sd .modal-header{ border:0; background:linear-gradient(135deg,var(--soft),var(--soft2)); padding:14px 16px; }
  .modal.sd .modal-title{ font-weight:800; color:var(--ink); }
  .modal.sd .close{ opacity:.7; font-size:24px; line-height:1; }
  .divider-title{ font-weight:800; color:var(--ink); margin:0 0 10px; border-bottom:1px dashed var(--line); padding-bottom:6px; }
  .pill{ display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:999px; font-weight:700; border:1px solid var(--line); background:#f8fafc; }
</style>

<section class="content">
  <div class="row">
    <div class="col-xs-12">
      <div id="me" class="alert alert-danger alert-dismissable" style="display:<?= $delinfo; ?>; margin-bottom:10px;">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-ban"></i> <?= e($_data['delete_text']); ?>!</h4>
        <?= e($_data['delete_buyer_information']); ?>
      </div>
      <div id="you" class="alert alert-success alert-dismissable" style="display:<?= $addinfo; ?>; margin-bottom:10px;">
        <button aria-hidden="true" data-dismiss="alert" class="close" type="button" aria-label="Close"><i class="fa fa-close"></i></button>
        <h4 style="margin-top:0;"><i class="icon fa fa-check"></i> <?= e($_data['success']); ?>!</h4>
        <?= e($msg); ?>
      </div>

      <div class="page-card">
        <div class="page-head">
          <h3 class="page-title"><i class="fa fa-users"></i> <?= e($_data['buyer_list']); ?></h3>
          <div class="toolbar" role="group" aria-label="Buyers toolbar">
            <a class="btn btn-success" href="<?= WEB_URL; ?>buyer/addbuyer.php" title="<?= e($_data['add_new_buyer_breadcam']); ?>">
              <i class="fa fa-plus"></i><?= e($_data['add_new_buyer_breadcam']); ?>
            </a>
            <a class="btn btn-primary" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['home_breadcam']); ?>">
              <i class="fa fa-dashboard"></i><?= e($_data['home_breadcam']); ?>
            </a>
            <div style="display:flex;gap:6px;align-items:center;">
              <input id="buyerSearch" class="input" placeholder="Search name, phone, business…" aria-label="Search buyers" />
              <span class="kbd">Ctrl /</span>
            </div>
          </div>
        </div>

        <div class="box-body" style="padding:12px;">
          <div class="table-wrap">
            <!-- NOTE: class changed to buyerTable (no 'sakotable' class) -->
            <table id="sakotable" class="table buyerTable table-bordered table-striped dt-responsive" style="width:100%;">
              <thead>
                <tr>
                  <th style="width:64px;"><?= e($_data['add_new_form_field_text_0']); ?></th>
                  <th><?= e($_data['add_new_form_field_1_text']); ?></th>
                  <th><?= e($_data['add_new_form_field_text_4']); ?></th>
                  <th>Business Name</th>
                  <th>Business Phone</th>
                  <th style="min-width:200px;"><?= e($_data['action_text']); ?></th>
                </tr>
              </thead>
              <tbody>
                <?php
                $result = mysqli_query($link,"SELECT * FROM buyers ORDER BY buyer_name ASC");
                while($row = mysqli_fetch_array($result)):
                  $image = WEB_URL . 'img/no_image.jpg';
                  if (!empty($row['image']) && file_exists(ROOT_PATH . '/img/upload/' . $row['image'])) {
                    $image = WEB_URL . 'img/upload/' . $row['image'];
                  }
                  $bbid = (int)$row['bbid'];
                ?>
                <tr>
                  <td><img class="avatar" src="<?= e($image); ?>" alt="<?= e($row['buyer_name']); ?> photo"></td>
                  <td><?= e($row['buyer_name']); ?></td>
                  <td><span class="pill"><i class="fa fa-phone"></i> <?= e($row['buyer_contact']); ?></span></td>
                  <td><?= e($row['business_name']); ?></td>
                  <td><?= e($row['business_phone']); ?></td>
                  <td>
                    <a class="btn btn-ghost btn-sm" data-toggle="tooltip" title="<?= e($_data['view_text']); ?>"
                       href="javascript:;" onclick="$('#buyer_view_<?= $bbid; ?>').modal('show');">
                      <i class="fa fa-eye"></i> View
                    </a>
                    <!-- <a class="btn btn-ghost btn-sm" data-toggle="tooltip" title="Assign Unit"
                       href="javascript:;" onclick="$('#assign_<?= $bbid; ?>').modal('show');">
                      <i class="fa fa-building-o"></i> Assign
                    </a> -->
                    <a class="btn btn-ghost btn-sm" data-toggle="tooltip" title="<?= e($_data['edit_text']); ?>"
                       href="<?= WEB_URL;?>buyer/addbuyer.php?id=<?= $bbid; ?>">
                      <i class="fa fa-pencil"></i> Edit
                    </a>
                    <a class="btn btn-danger btn-sm" data-toggle="tooltip" title="<?= e($_data['delete_text']); ?>"
                       href="javascript:;" onclick="deleteBuyer(<?= $bbid; ?>);">
                      <i class="fa fa-trash-o"></i> Delete
                    </a>

                    <!-- VIEW MODAL -->
                   <!-- Stylish Buyer Detail Modal -->
<style>
  /* Place this block once per page (ideally in your header) */
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --soft:#f8fafc; --soft2:#eef2ff; --card:#ffffff; --shadow:0 24px 60px rgba(2,6,23,.18);
    --brand:#2563eb; --ok:#16a34a;
  }
  .buyer-modal .modal-dialog{ max-width:720px; }
  .buyer-modal .modal-content{
    border:1px solid var(--line); border-radius:18px; overflow:hidden; background:var(--card); box-shadow:var(--shadow);
  }
  .buyer-modal .modal-header{
    border:0; padding:0; position:relative; min-height:120px;
    background:linear-gradient(135deg,var(--soft),var(--soft2));
  }
  .buyer-modal .cover{
    height:120px; background:radial-gradient(75% 100% at 20% 0%, rgba(37,99,235,.18) 0%, rgba(37,99,235,0) 60%);
  }
  .buyer-modal .close{
    position:absolute; right:10px; top:10px; font-size:20px; opacity:.8; z-index:2;
  }
  .buyer-modal .header-body{
    display:flex; gap:16px; align-items:center; padding:0 16px 16px; margin-top:-40px;
  }
  .buyer-modal .avatar{
    width:90px; height:90px; border-radius:16px; object-fit:cover; border:2px solid #fff; box-shadow:0 8px 24px rgba(2,6,23,.18);
    background:#fff;
  }
  .buyer-modal .title-wrap .name{
    font-weight:800; color:var(--ink); font-size:18px; line-height:1.2; margin-bottom:6px;
  }
  .buyer-modal .chips{ display:flex; gap:8px; flex-wrap:wrap; }
  .buyer-modal .chip{
    display:inline-flex; align-items:center; gap:6px; padding:6px 10px; border-radius:999px; border:1px solid var(--line);
    background:#fff; color:#111827; font-weight:700; font-size:12px;
  }
  .buyer-modal .chip i{ color:#64748b; }

  .buyer-modal .section-title{
    margin:0 0 10px; font-weight:800; color:var(--ink); display:flex; gap:8px; align-items:center;
  }
  .buyer-modal .section-title i{ color:#2563eb; }
  .buyer-modal .section{ padding:16px; }
  .buyer-modal .info-grid{
    display:grid; grid-template-columns:1fr 1fr; gap:14px;
  }
  @media (max-width: 560px){ .buyer-modal .info-grid{ grid-template-columns:1fr; } }

  .buyer-modal .info-item{
    border:1px dashed var(--line); border-radius:12px; padding:10px 12px; background:#fff;
  }
  .buyer-modal .info-item .label{ font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.3px; }
  .buyer-modal .info-item .value{ font-weight:700; color:var(--ink2); margin-top:4px; }

  .buyer-modal .attachments{
    display:flex; gap:10px; align-items:center; flex-wrap:wrap; padding:12px; border:1px dashed var(--line);
    border-radius:12px; background:#fff;
  }
  .buyer-modal .btn-soft{
    border-radius:10px; border:1px solid var(--line); background:#fff; color:#111827; font-weight:700;
  }
  .buyer-modal .btn-brand{
    border-radius:10px; background:var(--brand); color:#fff; font-weight:700; border:1px solid var(--brand);
  }
  .buyer-modal .modal-footer{
    border-top:1px solid var(--line); padding:12px 16px; display:flex; justify-content:flex-end; gap:10px;
  }
</style>

<div id="buyer_view_<?= $bbid; ?>" class="modal fade buyer-modal" tabindex="-1" role="dialog" aria-labelledby="buyerLabel_<?= $bbid; ?>" aria-hidden="true">
  <div class="modal-dialog modal-md" role="document">
    <div class="modal-content">

      <!-- Header -->
      <div class="modal-header">
        <button aria-label="Close" data-dismiss="modal" class="close" type="button">
          <span aria-hidden="true"><i class="fa fa-close"></i></span>
        </button>
        <div class="cover" aria-hidden="true"></div>
        <div class="header-body">
          <img src="<?= e($image); ?>" alt="<?= e($row['buyer_name']); ?> photo" class="avatar">
          <div class="title-wrap">
            <div class="name"><i class="fa fa-id-card-o"></i> <?= e($row['buyer_name']); ?></div>
            <div class="chips">
              <?php if (!empty($row['buyer_email'])): ?>
                <span class="chip" title="Email"><i class="fa fa-envelope"></i><?= e($row['buyer_email']); ?></span>
              <?php endif; ?>
              <span class="chip" title="Phone"><i class="fa fa-phone"></i><?= e($row['buyer_contact']); ?></span>
            </div>
          </div>
        </div>
      </div>

      <!-- Body -->
      <div class="modal-body">

        <div class="section">
          <h4 class="section-title"><i class="fa fa-info-circle"></i> <?= e($_data['details_information']); ?></h4>
          <div class="info-grid">
            <div class="info-item">
              <div class="label"><?= e($_data['add_new_form_field_1_text']); ?></div>
              <div class="value"><?= e($row['buyer_name']); ?></div>
            </div>
            <div class="info-item">
              <div class="label"><?= e($_data['add_new_form_field_text_2']); ?></div>
              <div class="value"><?= e($row['buyer_email']); ?></div>
            </div>
            <div class="info-item">
              <div class="label"><?= e($_data['add_new_form_field_text_4']); ?></div>
              <div class="value"><?= e($row['buyer_contact']); ?></div>
            </div>
            <div class="info-item">
              <div class="label"><?= e($_data['add_new_form_field_text_5']); ?></div>
              <div class="value"><?= e($row['buyer_address']); ?></div>
            </div>
            <div class="info-item">
              <div class="label">Business Name</div>
              <div class="value"><?= e($row['business_name']); ?></div>
            </div>
            <div class="info-item">
              <div class="label">Business Phone</div>
              <div class="value"><?= e($row['business_phone']); ?></div>
            </div>
            <div class="info-item">
              <div class="label">Nature of Business</div>
              <div class="value"><?= e($row['nature_of_business']); ?></div>
            </div>
          </div>
        </div>

        <div class="section">
          <h4 class="section-title"><i class="fa fa-paperclip"></i> Attachments</h4>
          <div class="attachments">
            <?php if (!empty($row['attachments'])): ?>
              <i class="fa fa-file-pdf-o" aria-hidden="true"></i>
              <span style="font-weight:700;color:var(--ink2);">Document attached</span>
              <a href="<?= e($row['attachments']); ?>" target="_blank" class="btn btn-soft btn-sm" rel="noopener">
                <i class="fa fa-external-link"></i> View Document
              </a>
            <?php else: ?>
              <span class="chip"><i class="fa fa-info-circle"></i> No document uploaded</span>
            <?php endif; ?>
          </div>
        </div>

      </div>

      <!-- Footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-soft" data-dismiss="modal">
          <i class="fa fa-close"></i> Close
        </button>
        <a href="<?= WEB_URL;?>buyer/addbuyer.php?id=<?= (int)$bbid; ?>" class="btn btn-brand">
          <i class="fa fa-pencil"></i> Edit Buyer
        </a>
      </div>

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


                    <!-- ASSIGN MODAL -->
                    <!-- <div id="assign_<?= $bbid; ?>" class="modal fade sd" tabindex="-1" role="dialog" aria-labelledby="assignLabel_<?= $bbid; ?>" aria-hidden="true">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header">
                            <h3 id="assignLabel_<?= $bbid; ?>" class="modal-title"><i class="fa fa-building-o"></i> Assign To Unit</h3>
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button"><span aria-hidden="true"><i class="fa fa-close"></i></span></button>
                          </div>
                          <form action="<?= $assign_unit_url ?>" method="post" id="frm_assign_<?= $bbid; ?>">
                            <div class="modal-body" style="padding:16px;">
                              <div style="display:flex; gap:12px; align-items:center; margin-bottom:12px;">
                                <img src="<?= e($image); ?>" alt="" class="avatar">
                                <div style="font-weight:800; color:var(--ink);"><?= e($row['buyer_name']); ?></div>
                              </div>

                              <div class="form-group" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                                <label for="bid_<?= $bbid; ?>" style="margin:0; min-width:120px;">Block <span style="color:#dc2626">*</span></label>
                                <select required name="bid" id="bid_<?= $bbid; ?>" class="form-control" style="flex:1;"
                                  onchange="getUnoccupiedUnitInfo('bid_<?= $bbid; ?>','uid_<?= $bbid; ?>')">
                                  <option value="">-- Select Block --</option>
                                  <?php
                                  $result_floor = mysqli_query($link,"SELECT * FROM blocks ORDER BY bid ASC");
                                  while($row_floor = mysqli_fetch_array($result_floor)){ ?>
                                    <option value="<?= (int)$row_floor['bid'];?>"><?= e($row_floor['b_name']);?></option>
                                  <?php } ?>
                                </select>
                              </div>

                              <div class="form-group" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
                                <label for="uid_<?= $bbid; ?>" style="margin:0; min-width:120px;"><?= e($_data['add_new_form_field_text_8']); ?> <span style="color:#dc2626">*</span></label>
                                <select required name="uid" id="uid_<?= $bbid; ?>" class="form-control" style="flex:1;">
                                  <option value="">-- Select Block First --</option>
                                </select>
                              </div>

                              <input type="hidden" name="tid" value="<?= $bbid; ?>" />
                            </div>

                            <div class="modal-footer" style="border-top:1px solid var(--line); padding:12px 16px;">
                              <button type="button" class="btn btn-default" data-dismiss="modal" style="border-radius:10px; border:1px solid var(--line);">
                                <i class="fa fa-close"></i> Cancel
                              </button>
                              <button type="submit" class="btn btn-success" style="border-radius:10px;">
                                <i class="fa fa-floppy-o"></i> Assign
                              </button>
                            </div>
                          </form>
                        </div>
                      </div>
                    </div> -->

                  </td>
                </tr>
                <?php endwhile; mysqli_close($link); $link = NULL; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>

    </div>
  </div>
</section>

<script>
  function deleteBuyer(Id){
    var go = function(){ window.location = '<?= WEB_URL; ?>buyer/buyerlist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') sweetConfirmDelete(go);
    else if (confirm('<?= addslashes($_data['confirm']); ?>')) go();
  }

  document.addEventListener('DOMContentLoaded', function(){
    // Hide alerts
    setTimeout(function(){
      var me  = document.getElementById('me');
      var you = document.getElementById('you');
      me  && (me.style.display  = 'none');
      you && (you.style.display = 'none');
    }, 3000);

    // Search shortcut
    var input = document.getElementById('buyerSearch');
    document.addEventListener('keydown', function(e){
      if ((e.ctrlKey || e.metaKey) && e.key === '/'){ e.preventDefault(); input && input.focus(); }
    });

    // ---- Zero-warnings DataTables init ----
    if (window.jQuery && $.fn.DataTable){
      // Silence any DT console popups (extra guard)
      $.fn.dataTable.ext.errMode = 'none';

      var $t = $('#sakotable');

      // If already a DT (maybe globally auto-initialized), destroy cleanly first
      if ($.fn.DataTable.isDataTable($t)) {
        $t.DataTable().destroy();        // fully tear down
        // remove DT-added width/sorting classes so re-init is clean
        $t.attr('style','');
        $t.find('thead th').removeClass('sorting sorting_asc sorting_desc');
      }

      // Now (re)initialize once, with destroy+retrieve guards
      var dt = $t.DataTable({
        destroy: true,   // allow future safe re-init if needed
        retrieve: true,  // if some code calls again, just return this instance
        order: [[1, 'asc']],
        responsive: true,
        autoWidth: false,
        pageLength: 25,
        deferRender: true,
        stateSave: true
      });

      // Connect the top-right search to DT search
      if (input) input.addEventListener('input', function(){ dt.search(this.value).draw(); });
    } else {
      // Fallback simple filter
      var input = document.getElementById('buyerSearch');
      function plainFilter(q){
        q = (q || '').toLowerCase().trim();
        var rows = document.querySelectorAll('#sakotable tbody tr');
        rows.forEach(function(tr){ tr.style.display = (!q || tr.textContent.toLowerCase().indexOf(q) !== -1) ? '' : 'none'; });
      }
      input && input.addEventListener('input', function(){ plainFilter(this.value); });
    }

    if (window.jQuery && $.fn.tooltip) $('[data-toggle="tooltip"]').tooltip();
  });
</script>

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