<?php
error_reporting(-1);
ini_set('display_errors', 1);

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

if (!check_login()) {
  header("Location: " . WEB_URL . "logout.php");
  die();
}
if (isset($_SESSION['login_type']) && $_SESSION['login_type'] !== "super") {
  header("Location: ".WEB_URL."logout.php");
  die();
}

/* ---------------------------
   Helpers
----------------------------*/
function e($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

function branchCount($link){
  $sql = mysqli_query($link, "SELECT COUNT(*) AS total_rows FROM tblbranch");
  if ($row = mysqli_fetch_assoc($sql)) {
    return ((int)$row['total_rows'] > 1);
  }
  return false;
}

/* ---------------------------
   Alerts
----------------------------*/
$delinfo = 'none';
$addinfo = 'none';
$msg     = "";

// Delete branch (only if more than 1 branch remains)
if (isset($_GET['id']) && $_GET['id'] !== '' && (int)$_GET['id'] > 0) {
  $del_id = (int)$_GET['id'];
  if (branchCount($link)) {
    if ($stmt = $link->prepare("DELETE FROM tblbranch WHERE branch_id = ? LIMIT 1")) {
      $stmt->bind_param('i', $del_id);
      $stmt->execute();
      $stmt->close();
      $delinfo = 'block';
    }
  } else {
    // keep at least one branch — show warning instead of deleting
    $addinfo = 'block';
    $msg = '<span style="color:#b45309;">'.e($_data['text_keep_one'] ?? 'At least one building must remain. You can rename the last building instead of deleting it.').'</span>';
  }
}

// Success messages
if (isset($_GET['m']) && $_GET['m'] === 'add') { $addinfo = 'block'; $msg = $_data['text_11']; }
if (isset($_GET['m']) && $_GET['m'] === 'up')  { $addinfo = 'block'; $msg = $_data['text_12']; }

?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <i class="fa fa-building"></i> <?= e($_data['text_14']);?>
  </h1>
  <ol class="breadcrumb">
    <li><a href="<?= WEB_URL?>dashboard.php"><i class="fa fa-dashboard"></i> <?= e($_data['text_19']);?></a></li>
    <li class="active"><?= e($_data['text_20']);?></li>
    <li class="active"><?= e($_data['text_14']);?></li>
  </ol>
</section>

<style>
  /* ===== Soft, modern UI ===== */
  :root{
    --ink:#0f172a; --ink2:#334155; --muted:#64748b; --line:#e5e7eb;
    --bg:#f6f7fb; --card:#ffffff; --brand:#2563eb; --ok:#10b981; --warn:#f59e0b; --danger:#ef4444;
    --shadow:0 12px 34px rgba(2,6,23,.10);
  }
  .content { background: var(--bg); }
  .content-header>h1{ font-weight:900; color:var(--ink); letter-spacing:.2px; }

  .toolbar { display:flex; gap:8px; justify-content:flex-end; margin-bottom:12px; }
  .btn{ border-radius:12px; font-weight:800; letter-spacing:.2px; }
  .btn-ghost{ background:#fff; color:#0f172a; border:1px solid var(--line); }
  .btn-ghost:hover{ background:#f8fafc; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); }
  .btn-success{ background:var(--ok); border-color:var(--ok); }

  .box.box-success{
    border:1px solid var(--line); border-radius:16px; box-shadow:var(--shadow); overflow:hidden;
  }
  .box .box-header{
    background:linear-gradient(180deg,#f8fafc,#fff); border-bottom:1px solid var(--line);
  }
  .box .box-header h3{ font-weight:900; color:var(--ink); margin:0; }

  /* Table polish */
  .table-polished{ width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table-polished thead th{
    background:#fafafa; color:var(--ink2); border:none; border-bottom:1px solid var(--line) !important;
    font-weight:900; text-transform:uppercase; font-size:12px; letter-spacing:.35px; padding:10px 12px;
  }
  .table-polished tbody tr{
    background:#fff; border:1px solid var(--line);
  }
  .table-polished tbody td{ padding:12px; border-top:1px solid var(--line); vertical-align:middle !important; }
  .table-polished tbody tr:first-child td{ border-top:none; }
  .table-polished tbody tr td:first-child{ border-left:1px solid var(--line); border-radius:12px 0 0 12px; }
  .table-polished tbody tr td:last-child{ border-right:1px solid var(--line); border-radius:0 12px 12px 0; }
  .table-polished tbody tr:hover{ box-shadow:0 6px 20px rgba(2,6,23,.06); }

  .actions{ display:flex; gap:6px; }
  .actions .btn{ padding:6px 10px; }

  /* Badges */
  .status-pill{
    display:inline-flex; align-items:center; gap:6px; padding:4px 10px; font-size:12px; font-weight:800; letter-spacing:.2px;
    border-radius:999px; border:1px solid;
  }
  .status-on{ background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
  .status-off{ background:#fef2f2; color:#7f1d1d; border-color:#fecaca; }

  /* Alerts */
  .alert{ border-radius:12px; }

  /* Modal */
  .modal-content{
    border-radius:16px; border:1px solid var(--line); box-shadow:0 22px 60px rgba(2,6,23,.18);
  }
  .modal-header{
    background:linear-gradient(180deg,#f8fafc,#fff); border-bottom:1px solid var(--line);
    display:flex; align-items:center; justify-content:space-between;
  }
  .modal-title{ font-weight:900; color:var(--ink); }
  .branch-hero{ display:flex; align-items:center; gap:12px; }
  .branch-avatar{
    width:64px; height:64px; border-radius:14px; object-fit:cover; border:1px solid var(--line);
    box-shadow:0 8px 20px rgba(2,6,23,.10);
  }
  .kv{ display:flex; gap:8px; margin-bottom:8px; }
  .kv .k{ min-width:180px; color:var(--muted); font-weight:800; }
  .kv .v{ color:#0f172a; font-weight:700; }
</style>

<section class="content">
  <!-- Alerts -->
  <div id="delAlert" 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['text_13']);?>
  </div>
  <div id="msgAlert" 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>
    <?= $msg; ?>
  </div>

  <!-- Toolbar -->
  <div class="toolbar">
    <a class="btn btn-success" data-toggle="tooltip" href="<?= WEB_URL; ?>branch/addbranch.php" title="<?= e($_data['text_1']);?>">
      <i class="fa fa-plus"></i> <?= e($_data['text_1']);?>
    </a>
    <a class="btn btn-ghost" data-toggle="tooltip" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['text_17']);?>">
      <i class="fa fa-dashboard"></i> <?= e($_data['text_17']);?>
    </a>
  </div>

  <!-- List -->
  <div class="box box-success">
    <div class="box-header">
      <h3 class="box-title"><i class="fa fa-list-ul"></i> <?= e($_data['text_14']);?></h3>
    </div>
    <div class="box-body">
      <div style="margin-bottom:10px;color:#b45309;background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:8px 10px;">
        <strong>Heads up:</strong> If you delete all buildings the system will stop working. Keep at least one building; you can rename the last one instead of deleting it.
      </div>

      <div class="table-responsive">
        <table id="branchTable" class="table table-polished table-bordered dt-responsive">
          <thead>
            <tr>
              <th><?= e($_data['text_4']);?></th>
              <th><?= e($_data['text_5']);?></th>
              <th><?= e($_data['text_6']);?></th>
              <th><?= e($_data['text_7']);?></th>
              <th><?= e($_data['text_233']);?></th>
              <th><?= e($_data['action_text']);?></th>
            </tr>
          </thead>
          <tbody>
          <?php
          $result = mysqli_query($link, "
            SELECT b.*, y.xyear 
            FROM tblbranch b 
            LEFT JOIN tbl_add_year_setup y ON b.building_make_year = y.y_id 
            ORDER BY branch_id DESC
          ");
          while ($row = mysqli_fetch_assoc($result)) {
            $img = WEB_URL . 'img/no_image.jpg'; // reset per row
            if (!empty($row['building_image'])) {
              $candidate = ROOT_PATH . '/img/upload/' . $row['building_image'];
              if (file_exists($candidate)) {
                $img = WEB_URL . 'img/upload/' . $row['building_image'];
              }
            }
            $modal_id = 'branch_view_' . (int)$row['branch_id'];
          ?>
            <tr>
              <td>
                <div style="display:flex;align-items:center;gap:10px;">
                  <img src="<?= e($img)?>" alt="Building" style="width:40px;height:40px;border-radius:10px;object-fit:cover;border:1px solid var(--line);">
                  <div style="font-weight:900;color:#0f172a;"><?= e($row['branch_name']); ?></div>
                </div>
              </td>
              <td><?= e($row['b_email']); ?></td>
              <td><?= e($row['b_contact_no']); ?></td>
              <td><?= e($row['b_address']); ?></td>
              <td>
                <?php if ((bool)$row['b_status']) { ?>
                  <span class="status-pill status-on"><i class="fa fa-check"></i> Active</span>
                <?php } else { ?>
                  <span class="status-pill status-off"><i class="fa fa-times"></i> Inactive</span>
                <?php } ?>
              </td>
              <td>
                <div class="actions">
                  <a class="btn btn-success ams_btn_special" data-toggle="tooltip" href="javascript:void(0);" onclick="$('#<?= $modal_id ?>').modal('show');" title="<?= e($_data['view_text']);?>">
                    <i class="fa fa-eye"></i>
                  </a>
                  <a class="btn btn-warning ams_btn_special" data-toggle="tooltip" href="<?= WEB_URL;?>branch/addbranch.php?id=<?= (int)$row['branch_id']; ?>" title="<?= e($_data['edit_text']);?>">
                    <i class="fa fa-pencil"></i>
                  </a>
                  <a class="btn btn-danger ams_btn_special" data-toggle="tooltip" href="javascript:void(0);" onclick="deleteBranch(<?= (int)$row['branch_id']; ?>);" title="<?= e($_data['delete_text']);?>">
                    <i class="fa fa-trash-o"></i>
                  </a>
                </div>

                <!-- View Modal -->
               <!-- Stylish Branch View Modal -->
<style>
  /* ===== Branch Modal (scoped) ===== */
  .bmodal .modal-content{
    border-radius:16px; border:1px solid #e5e7eb;
    box-shadow:0 28px 80px rgba(2,6,23,.18);
    overflow:hidden;
    font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Apple Color Emoji", "Segoe UI Emoji";
  }
  .bmodal .modal-header{
    display:flex; align-items:center; justify-content:space-between;
    padding:14px 16px; border-bottom:1px solid #e5e7eb;
    background:linear-gradient(180deg,#f8fafc,#ffffff);
  }
  .bmodal .modal-title{
    margin:0; font-weight:900; color:#0f172a; letter-spacing:.2px;
    display:flex; align-items:center; gap:10px;
  }
  .bmodal .title-icon{
    width:36px; height:36px; border-radius:10px; background:#eaf2ff;
    display:inline-flex; align-items:center; justify-content:center; color:#2563eb;
  }
  .bmodal .modal-body{ padding:16px 18px; }

  /* Hero */
  .bmodal .branch-hero{
    display:flex; align-items:center; gap:14px;
    padding:10px 12px; border:1px solid #e5e7eb; border-radius:14px;
    background:linear-gradient(180deg,#f8fafc,#fff);
  }
  .bmodal .branch-avatar{
    width:74px; height:74px; border-radius:14px; object-fit:cover;
    border:1px solid #e5e7eb; box-shadow:0 10px 26px rgba(2,6,23,.12);
  }
  .bmodal .branch-name{ font-size:20px; font-weight:900; color:#0f172a; }
  .bmodal .status-pill{
    display:inline-flex; align-items:center; gap:6px;
    padding:4px 10px; border-radius:999px; font-weight:800; font-size:12px; letter-spacing:.2px;
    border:1px solid;
  }
  .bmodal .status-on{ background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
  .bmodal .status-off{ background:#fef2f2; color:#7f1d1d; border-color:#fecaca; }

  /* Quick actions */
  .bmodal .qa{
    display:flex; flex-wrap:wrap; gap:8px; margin-top:8px;
  }
  .bmodal .btn-soft{
    background:#fff; color:#0f172a; border:1px solid #e5e7eb; border-radius:10px;
    font-weight:700; padding:6px 10px;
  }
  .bmodal .btn-soft:hover{ background:#f8fafc; }

  /* Sections */
  .bmodal .section-title{
    margin:14px 2px 10px; font-weight:900; color:#0f172a;
    display:flex; align-items:center; gap:8px;
  }
  .bmodal .section-title i{ color:#2563eb; }

  /* Key-Value Grid */
  .bmodal .kv{ display:flex; gap:8px; align-items:flex-start; padding:8px 0; }
  .bmodal .kv .k{
    min-width:200px; color:#64748b; font-weight:800;
    display:inline-flex; align-items:center; gap:8px;
  }
  .bmodal .kv .k i{ color:#334155; opacity:.7; width:16px; text-align:center; }
  .bmodal .kv .v{ color:#0f172a; font-weight:700; }

  /* Footer */
  .bmodal .modal-footer{
    display:flex; gap:8px; justify-content:flex-end; border-top:1px solid #e5e7eb;
    padding:12px 16px;
  }
  .bmodal .btn-ghost{ background:#fff; border:1px solid #e5e7eb; color:#0f172a; border-radius:10px; font-weight:800; }
  .bmodal .btn-ghost:hover{ background:#f8fafc; }
  .bmodal .btn-primary{ background:#2563eb; border-color:#2563eb; border-radius:10px; font-weight:800; }
</style>

<div id="<?= $modal_id ?>" class="modal fade bmodal" tabindex="-1" role="dialog" aria-hidden="true" aria-labelledby="<?= $modal_id ?>_title">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">

      <!-- Header -->
      <div class="modal-header">
        <h3 class="modal-title" id="<?= $modal_id ?>_title">
          <span class="title-icon"><i class="fa fa-building-o"></i></span>
          <?= e($_data['text_16']);?>
        </h3>
        <button aria-label="Close" data-dismiss="modal" class="close" type="button" style="opacity:.8;">
          <span aria-hidden="true"><i class="fa fa-close"></i></span>
        </button>
      </div>

      <!-- Body -->
      <div class="modal-body">
        <!-- Hero -->
        <div class="branch-hero">
          <img class="branch-avatar" src="<?= e($img)?>" alt="<?= e($row['branch_name']);?>">
          <div>
            <div class="branch-name"><?= e($row['branch_name']); ?></div>
            <?php if ((bool)$row['b_status']) { ?>
              <span class="status-pill status-on"><i class="fa fa-check"></i> Active</span>
            <?php } else { ?>
              <span class="status-pill status-off"><i class="fa fa-times"></i> Inactive</span>
            <?php } ?>

            <!-- Quick actions (only show when data exists) -->
            <div class="qa">
              <?php if (!empty($row['b_email'])): ?>
                <a class="btn btn-soft btn-xs" href="mailto:<?= e($row['b_email']); ?>"><i class="fa fa-envelope"></i> Email</a>
                <button type="button" class="btn btn-soft btn-xs" onclick="bmodalCopy('<?= e($row['b_email']); ?>')" title="Copy email"><i class="fa fa-copy"></i> Copy</button>
              <?php endif; ?>
              <?php if (!empty($row['b_contact_no'])): ?>
                <a class="btn btn-soft btn-xs" href="tel:<?= e($row['b_contact_no']); ?>"><i class="fa fa-phone"></i> Call</a>
                <button type="button" class="btn btn-soft btn-xs" onclick="bmodalCopy('<?= e($row['b_contact_no']); ?>')" title="Copy phone"><i class="fa fa-copy"></i> Copy</button>
              <?php endif; ?>
              <?php if (!empty($row['b_address'])): ?>
                <a class="btn btn-soft btn-xs" target="_blank" href="<?= 'https://www.google.com/maps/search/?api=1&query='.urlencode($row['b_address']); ?>">
                  <i class="fa fa-map-marker"></i> Map
                </a>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Details -->
        <div class="section-title"><i class="fa fa-list-ul"></i> <?= e($_data['details_information']);?></div>
        <div class="row">
          <div class="col-sm-6">
            <div class="kv"><div class="k"><i class="fa fa-building"></i> <?= e($_data['text_4']);?> :</div><div class="v"><?= e($row['branch_name']); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-envelope-o"></i> <?= e($_data['text_5']);?> :</div><div class="v"><?= e($row['b_email'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-phone"></i> <?= e($_data['text_6']);?> :</div><div class="v"><?= e($row['b_contact_no'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-shield"></i> <?= e($_data['text_144']);?> :</div><div class="v"><?= e($row['security_guard_mobile'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-user"></i> <?= e($_data['text_155']);?> :</div><div class="v"><?= e($row['secrataty_mobile'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-user-secret"></i> <?= e($_data['text_166']);?> :</div><div class="v"><?= e($row['moderator_mobile'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-calendar"></i> <?= e($_data['text_177']);?> :</div><div class="v"><?= e($row['xyear'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-map-marker"></i> <?= e($_data['text_7']);?> :</div><div class="v"><?= e($row['b_address'] ?: '—'); ?></div></div>
          </div>
          <div class="col-sm-6">
            <div class="kv"><div class="k"><i class="fa fa-industry"></i> <?= e($_data['text_200']);?> :</div><div class="v"><?= e($row['builder_company_name'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-phone-square"></i> <?= e($_data['text_211']);?> :</div><div class="v"><?= e($row['builder_company_phone'] ?: '—'); ?></div></div>
            <div class="kv"><div class="k"><i class="fa fa-map"></i> <?= e($_data['text_222']);?> :</div><div class="v"><?= e($row['builder_company_address'] ?: '—'); ?></div></div>
          </div>
        </div>
      </div>

      <!-- Footer -->
      <div class="modal-footer">
        <button type="button" class="btn btn-ghost" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
        <a class="btn btn-primary" href="<?= WEB_URL;?>branch/addbranch.php?id=<?= (int)$row['branch_id']; ?>">
          <i class="fa fa-pencil"></i> <?= e($_data['edit_text']);?>
        </a>
      </div>

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

                <!-- /View Modal -->
              </td>
            </tr>
          <?php } mysqli_close($link); $link = NULL; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</section>

<script type="text/javascript">
  function deleteBranch(Id){
    var go = function(){ window.location = 'branchlist.php?id=' + Id; };
    if (typeof sweetConfirmDelete === 'function') {
      sweetConfirmDelete(go);
    } else {
      if (confirm('<?= addslashes($_data['delete_text']);?>?')) go();
    }
  }

  // Fade out alerts
  setTimeout(function(){
    var a = document.getElementById('delAlert'); if (a) a.style.display = 'none';
    var b = document.getElementById('msgAlert'); if (b) b.style.display = 'none';
  }, 3500);

  // Enhance table if DataTables is available
  (function($){
    if (!$ || !$.fn || !$.fn.DataTable) return;
    $('#branchTable').DataTable({
      pageLength: 10,
      order: [],
      responsive: true,
      columnDefs: [{ orderable: false, targets: [5] }],
      language: {
        search: "Quick Search:",
        searchPlaceholder: "Type to filter…"
      }
    });
  })(window.jQuery);
</script>
<?php include_once('../footer.php'); ?>
