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

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

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

$add_payment_url = WEB_URL . "service_fee/add_payment.php";

/* ---------------- Utilities ---------------- */
function v($arr, $key, $default = '') { return isset($arr[$key]) ? $arr[$key] : $default; }
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function decode_currency($c) {
  $s = html_entity_decode((string)$c, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  $u = mb_strtoupper($s, 'UTF-8');
  // Normalize common Ghana cedi variants / broken symbols
  if ($u === 'GHS' || strpos($u,'GH') !== false || strpos($s,'¢') !== false) return '₵';
  if ($s === '?' || $s === '' || $s === '�') return '₵';
  return $s;
}

/* ---------------- Handle Actions (delete + messages) ---------------- */
$delinfo = 'none';
$addinfo = 'none';
$msg = null;

$data = get_input_serilization();

/* Delete service fee + related with transaction (prepared) */
if (isset($data['action']) && $data["action"] === "delete" && isset($data['id']) && (int)$data['id'] > 0) {
  $rid = (int)$data['id'];
  try {
    $link->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);

    $s1 = $link->prepare("DELETE FROM tenant_service_accounts WHERE rid = ?");
    $s1->bind_param("i", $rid); $s1->execute(); $s1->close();

    $s2 = $link->prepare("DELETE FROM service_payment_updates WHERE rent_id = ?");
    $s2->bind_param("i", $rid); $s2->execute(); $s2->close();

    $s3 = $link->prepare("DELETE FROM service_main_account WHERE rent_id = ?");
    $s3->bind_param("i", $rid); $s3->execute(); $s3->close();

    $s4 = $link->prepare("DELETE FROM foreign_currency_service_main_account WHERE rent_id = ?");
    $s4->bind_param("i", $rid); $s4->execute(); $s4->close();

    $s5 = $link->prepare("DELETE FROM service_fee WHERE id = ?");
    $s5->bind_param("i", $rid); $s5->execute(); $s5->close();

    $link->commit();

    $_SESSION["message"] = $_data['delete_rent_information'];
    $_SESSION["message_type"] = "success";
  } catch (Exception $e) {
    if ($link->errno) { $link->rollback(); }
    $_SESSION["message"] = "Failed to delete service fee: " . $e->getMessage();
    $_SESSION["message_type"] = "error";
  }

  header("Location: " . WEB_URL . "service_fee/servicelist.php");
  exit;
}

/* Success banners from add/update */
if (isset($data['m']) && $data['m'] == 'add') { $addinfo = 'block'; $msg = $_data['added_service_fee_successfully']; }
if (isset($data['m']) && $data['m'] == 'up')  { $addinfo = 'block'; $msg = $_data['update_service_fee_successfully']; }

/* Session message relay */
if (isset($_SESSION["message"])) {
  if (isset($_SESSION["message_type"]) && $_SESSION["message_type"] === "error") {
    $delinfo = 'block'; $addinfo = 'none';
  } else {
    $addinfo = 'block'; $delinfo = 'none';
  }
  $msg = $_SESSION["message"];
  unset($_SESSION["message"], $_SESSION["message_type"]);
}

/* ---------------- Filters (q, status, window) ---------------- */
$q       = trim((string)v($data, 'q'));
$status  = trim((string)v($data, 'status'));   // '', 'unpaid','partial','full'
$window  = trim((string)v($data, 'window'));   // '', 'today','7','30','90','ended'

$where = [];
if ($q !== '') {
  $esc = mysqli_real_escape_string($link, $q);
  $where[] = "(r_name LIKE '%{$esc}%' OR b_name LIKE '%{$esc}%' OR unit_no LIKE '%{$esc}%')";
}
if ($status !== '') {
  if ($status === 'full')    $where[] = "(amt_paid >= total_rent AND total_rent > 0)";
  if ($status === 'partial') $where[] = "(amt_paid > 0 AND amt_paid < total_rent)";
  if ($status === 'unpaid')  $where[] = "(amt_paid = 0 AND total_rent > 0)";
}
if ($window !== '') {
  if ($window === 'ended') {
    $where[] = "(DATE(end_date) < CURDATE())";
  } elseif ($window === 'today') {
    $where[] = "(DATE(end_date) = CURDATE())";
  } else {
    $n = (int)$window;
    if ($n > 0) {
      $where[] = "(DATE(end_date) >= CURDATE() AND DATE(end_date) <= DATE_ADD(CURDATE(), INTERVAL {$n} DAY))";
    }
  }
}
$where_sql = count($where) ? ('WHERE ' . implode(' AND ', $where)) : '';

/* ---------------- Fetch rows: newest first (last entry first) ---------------- */
$sql = "SELECT * FROM service_tenant_unit_view {$where_sql} ORDER BY id DESC";
$result = mysqli_query($link, $sql);
?>
<!-- Content Header -->
<section class="content-header">
  <h1 style="display:flex;align-items:center;gap:10px;">
    <i class="fa fa-list-ul"></i> <?= e($_data['service_list']);?>
  </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_service_information_breadcam']);?></li>
    <li class="active"><?= e($_data['service_list']);?></li>
  </ol>
</section>

<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;
    --ok:#16a34a; --brand:#2563eb; --warn:#d97706; --danger:#dc2626;
    --soft:#f8fafc; --soft2:#eef2ff;
  }
  .content-wrapper, .box, .table, label, .btn, .alert {
    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 { background:#fff; border:1px solid var(--line); border-radius:16px;
    box-shadow:0 16px 40px rgba(2,6,23,.06); overflow:hidden; margin-bottom:18px; }
  .card-header { display:flex; align-items:center; justify-content:space-between; gap:12px;
    padding:16px 18px; background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line); }
  .card-title { margin:0; font-weight:800; color:var(--ink); letter-spacing:.2px; }

  .toolbar { display:flex; gap:8px; flex-wrap:wrap; }
  .btn-pill { border-radius:999px !important; padding:8px 14px; font-weight:700; letter-spacing:.2px; }
  .btn-primary{ background:var(--brand); border-color:var(--brand); color:#fff; }
  .btn-primary:hover{ background:#1d4ed8; border-color:#1d4ed8; }
  .btn-success{ background:var(--ok); border-color:var(--ok); color:#fff; }
  .btn-success:hover{ background:#15803d; border-color:#15803d; }
  .btn-warning{ background:#f59e0b; border-color:#f59e0b; color:#111827; }
  .btn-warning:hover{ background:#d97706; border-color:#d97706; }
  .btn-danger{ background:var(--danger); border-color:var(--danger); color:#fff; }

  .filter-row { display:grid; grid-template-columns:1fr 180px 180px auto; gap:10px;
    padding:14px 16px; border-bottom:1px dashed var(--line); background:#fbfdff; }
  @media(max-width: 900px){ .filter-row { grid-template-columns:1fr 1fr; } }
  .input, .select { width:100%; border:1px solid var(--line); border-radius:12px; padding:8px 12px; outline:none; }
  .input:focus, .select:focus { border-color:#93c5fd; box-shadow:0 0 0 3px rgba(59,130,246,.15); }

  .table-polished { width:100%; border-collapse:separate; border-spacing:0 8px; }
  .table-polished thead th{ font-weight:800; color:var(--ink-2); text-transform:uppercase; font-size:12px; letter-spacing:.35px;
    border-bottom:1px solid var(--line); 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; }
  .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; }
  .sub{ display:block; color:var(--muted); font-size:12px; margin-top:2px; }

  .chip{ display:inline-block; padding:4px 10px; border-radius:999px; font-size:12px; font-weight:700; border:1px solid var(--line); background:#fff; }
  .chip.gray{ color:#475569; }
  .chip.green{ background:#ecfdf5; color:#065f46; border-color:#a7f3d0; }
  .chip.warn{ background:#fff7ed; color:#9a3412; border-color:#fed7aa; }
  .chip.red{ background:#fef2f2; color:#991b1b; border-color:#fecaca; }

  .status-badge{ font-size:12px; font-weight:700; border-radius:999px; padding:4px 10px; }
  .status-partial{ background:#fef3c7; color:#92400e; }
  .status-full{ background:#dbeafe; color:#1e3a8a; }
  .status-unpaid{ background:#fee2e2; color:#991b1b; }

  .alert{ border-radius:12px; }

  .modal-content{ border-radius:16px; overflow:hidden; }
  .modal-header.fancy{ background:linear-gradient(135deg,var(--soft),var(--soft2)); border-bottom:1px solid var(--line); }
  .modal-title{ display:flex; align-items:center; gap:8px; font-weight:800; color:var(--ink); }

  /* Info modal styles */
  .info-modal .profile-card{ display:flex; flex-direction:column; align-items:center; gap:10px; border:1px dashed #e5e7eb;
    border-radius:14px; padding:14px; background:#f8fafc; }
  .info-modal .avatar{ width:96px; height:96px; border-radius:50%; object-fit:cover; border:2px solid #e5e7eb; }
  .info-modal .tenant-name{ font-weight:900; color:#0f172a; font-size:18px; letter-spacing:.2px; }
  .info-modal .chip{ display:inline-flex; align-items:center; gap:6px; padding:4px 10px; border-radius:999px; font-weight:700; font-size:12px; border:1px solid transparent; }
  .info-modal .chip-id{ background:#eef2ff; border-color:#e0e7ff; color:#3730a3; }
  .info-modal .chip-money{ background:#ecfeff; border-color:#bae6fd; color:#075985; }
  .info-modal .chip-date{ background:#fefce8; border-color:#fde68a; color:#7c2d12; }
  .info-modal .chip-start{ background:#ecfdf5; border-color:#a7f3d0; color:#065f46; }
  .info-modal .chip-end{ background:#fef2f2; border-color:#fecaca; color:#7f1d1d; }
  .info-modal .section-title{ font-weight:800; margin:0 0 10px; color:#0f172a; display:flex; align-items:center; gap:6px; }
  .info-modal .info-grid{ display:grid; grid-template-columns:1fr 1fr; gap:12px 20px; }
  @media (max-width: 480px){ .info-modal .info-grid{ grid-template-columns:1fr; } }
  .info-modal .grid-col{ display:grid; gap:10px; }
  .info-modal .kv{ display:grid; grid-template-columns:140px 1fr; gap:8px; align-items:center; }
  @media (max-width: 480px){ .info-modal .kv{ grid-template-columns:1fr; gap:2px; } }
  .info-modal .k{ color:#64748b; font-weight:700; text-transform:uppercase; letter-spacing:.3px; font-size:11px; }
  .info-modal .v{ color:#0f172a; font-weight:800; }

  /* Payment modal */
  .payment-modal .tenant-card{ display:flex; align-items:center; gap:14px; border:1px dashed #e5e7eb; border-radius:14px; padding:12px 14px; background:#f8fafc; }
  .payment-modal .avatar{ width:72px; height:72px; border-radius:50%; object-fit:cover; border:2px solid #e5e7eb; }
  .payment-modal .tenant-info{ display:grid; gap:4px; }
  .payment-modal .tenant-name{ font-weight:800; color:#0f172a; font-size:16px; }
  .payment-modal .tenant-balance .label{ color:#64748b; font-weight:700; margin-right:8px; text-transform:uppercase; font-size:11px; }
  .payment-modal .tenant-balance .chip{ display:inline-flex; align-items:baseline; gap:4px; background:#ecfeff; border:1px solid #bae6fd; color:#075985; padding:4px 10px; border-radius:999px; font-weight:800; }
  .slim-progress{ margin-top:8px; height:8px; background:#f1f5f9; border-radius:999px; box-shadow: inset 0 0 0 1px #e5e7eb; }
  .slim-progress .progress-bar{ background: linear-gradient(90deg, #34d399, #10b981); border-radius:999px; }

  .form-group.has-error .form-control { border-color: #ef4444; box-shadow: none; }
  .form-group.has-error .help-block { color: #b91c1c; }
  .form-group.has-success .form-control { border-color: #10b981; box-shadow: none; }
  .form-group.has-success .help-block { color: #065f46; }
</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"><span aria-hidden="true"><i class="fa fa-close"></i></span></button>
        <h4><i class="icon fa fa-ban"></i> <?= $msg ? "Warning" : e($_data['delete_text']);?>!</h4>
        <?= e($msg ?? $_data['delete_rent_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>

      <!-- Card + filters -->
      <div class="card">
        <div class="card-header">
          <h3 class="card-title"><i class="fa fa-home"></i> <?= e($_data['service_list']);?></h3>
          <div class="toolbar">
            <a class="btn btn-success btn-pill" data-toggle="tooltip" href="<?= WEB_URL; ?>service_fee/addservicefee.php" title="<?= e($_data['add_new_service_information_breadcam']);?>">
              <i class="fa fa-plus"></i> <?= e($_data['add_new_service_information_breadcam']);?>
            </a>
            <a class="btn btn-primary btn-pill" data-toggle="tooltip" href="<?= WEB_URL; ?>dashboard.php" title="<?= e($_data['home_breadcam']);?>">
              <i class="fa fa-dashboard"></i> <?= e($_data['home_breadcam']);?>
            </a>
          </div>
        </div>

        <form method="get" class="filter-row">
          <input type="text" class="input" name="q" placeholder="Search tenant, block, unit…" value="<?= e($q); ?>">
          <select class="select" name="status">
            <option value="">All Statuses</option>
            <option value="unpaid"  <?= ($status==='unpaid'?'selected':'') ?>>Unpaid</option>
            <option value="partial" <?= ($status==='partial'?'selected':'') ?>>Partial</option>
            <option value="full"    <?= ($status==='full'?'selected':'') ?>>Paid</option>
          </select>
          <select class="select" name="window">
            <option value="">Any End Date</option>
            <option value="today" <?= ($window==='today'?'selected':'') ?>>Ends today</option>
            <option value="7"     <?= ($window==='7'?'selected':'') ?>>Ends in 7 days</option>
            <option value="30"    <?= ($window==='30'?'selected':'') ?>>Ends in 30 days</option>
            <option value="90"    <?= ($window==='90'?'selected':'') ?>>Ends in 90 days</option>
            <option value="ended" <?= ($window==='ended'?'selected':'') ?>>Already Ended</option>
          </select>
          <div style="display:flex; gap:8px;">
            <button type="submit" class="btn btn-primary btn-pill"><i class="fa fa-search"></i> Filter</button>
            <a href="<?= WEB_URL; ?>service_fee/servicelist.php" class="btn btn-pill" style="border:1px solid var(--line); background:#fff;">Reset</a>
          </div>
        </form>

        <!-- Table -->
        <div class="box-body" style="padding:14px 16px 18px;">
          <div class="table-responsive">
            <table id="serviceTable" class="table table-polished table-bordered dt-responsive">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Tenant</th>
                  <th>Block</th>
                  <th>Unit</th>
                  <th>Start Date</th>
                  <th>End Date</th>
                  <th>Paid</th>
                  <th>Balance</th>
                  <th><?= e($_data['add_new_form_field_text_144']); // Total ?></th>
                  <th>Status</th>
                  <th><?= e($_data['action_text']);?></th>
                </tr>
              </thead>
              <tbody>
              <?php
              $today = new DateTime('today');
              while($row = mysqli_fetch_array($result)){
                $id          = (int)$row['id'];
                $r_name      = e($row['r_name']);
                $b_name      = e($row['b_name']);
                $unit_no     = e($row['unit_no']);
                $start_date  = date("jS F, Y", strtotime($row['start_date']));
                $end_date    = date("jS F, Y", strtotime($row['end_date']));

                $currency    = decode_currency($row['rate_currency']);
                $total_rent  = (float)$row['total_rent'];
                $amt_paid    = (float)$row['amt_paid'];
                $balance     = max(0, $total_rent - $amt_paid);

                // Payment status chip
                if ($amt_paid > 0 && $amt_paid < $total_rent) {
                  $payStatus = '<span class="status-badge status-partial">Partial</span>';
                } elseif ($amt_paid >= $total_rent && $total_rent > 0) {
                  $payStatus = '<span class="status-badge status-full">Paid</span>';
                } else {
                  $payStatus = '<span class="status-badge status-unpaid">Unpaid</span>';
                }

                // Due / Ended chip
                $endDt = new DateTime($row['end_date']);
                $diffDays = (int)((new DateTime('today'))->diff($endDt)->format('%r%a'));
                if ($diffDays === 0) {
                  $dueChip = '<span class="chip red">Due today</span>';
                } elseif ($diffDays < 0) {
                  $dueChip = '<span class="chip green">Ended</span>';
                } elseif ($diffDays <= 7) {
                  $dueChip = '<span class="chip warn">Due soon</span>';
                } else {
                  $dueChip = '<span class="chip gray">OK</span>';
                }

                // Photo
                $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'];
                }
              ?>
                <tr>
                  <td><?= $id; ?></td>
                  <td>
                    <div style="font-weight:800; color:#0f172a;"><?= $r_name; ?></div>
                    <span class="sub"><?= $dueChip; ?></span>
                  </td>
                  <td><?= $b_name; ?></td>
                  <td><?= $unit_no; ?></td>
                  <td><?= $start_date; ?></td>
                  <td><?= $end_date; ?></td>
                  <td><?= $currency . " " . number_format($amt_paid, 2); ?></td>
                  <td><?= $currency . " " . number_format($balance, 2); ?></td>
                  <td><?= $currency . " " . number_format($total_rent, 2); ?></td>
                  <td><?= $payStatus; ?></td>
                  <td>
                    <a target="_blank" class="btn btn-info ams_btn_special" title="<?= e($_data['invoice_no']);?>" data-toggle="tooltip" href="<?= WEB_URL;?>service_fee/invoice.php?rentid=<?= $id; ?>">
                      <i class="fa fa-file-text-o"></i>
                    </a>

                    <a class="btn btn-success ams_btn_special" data-toggle="tooltip" href="javascript:;" title="<?= e($_data['view_text']);?>" onclick="$('#info_view_<?= $id; ?>').modal('show');">
                      <i class="fa fa-eye"></i>
                    </a>

                    <?php if ($balance > 0): ?>
                      <!-- Add Payment button ONLY when not fully paid -->
                      <a class="btn btn-primary ams_btn_special" data-toggle="tooltip" href="javascript:;" title="Add Payment" onclick="$('#payment_view_<?= $id; ?>').modal('show');">
                        <i class="fa fa-money"></i>
                      </a>
                    <?php endif; ?>

                    <a class="btn btn-danger ams_btn_special" data-toggle="tooltip" title="<?= e($_data['delete_text']);?>" href="javascript:;" onclick="deleteService(<?= $id; ?>);">
                      <i class="fa fa-trash-o"></i>
                    </a>

                    <!-- Info Modal -->
                    <div id="info_view_<?= $id; ?>" class="modal fade info-modal" tabindex="-1" role="dialog" aria-hidden="true" aria-labelledby="infoModalTitle_<?= $id; ?>">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header fancy">
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                              <span aria-hidden="true"><i class="fa fa-close"></i></span>
                            </button>
                            <h3 id="infoModalTitle_<?= $id; ?>" class="modal-title">
                              <i class="fa fa-info-circle"></i> <?= e($_data['fare_details']); ?>
                            </h3>
                          </div>

                          <div class="modal-body">
                            <div class="profile-card" align="center">
                              <img class="avatar" src="<?= $image; ?>" alt="Photo of <?= $r_name; ?>">
                              <div class="tenant-name"><?= $r_name; ?></div>
                              <div class="meta-line">
                                <span class="chip chip-id" title="Invoice No.">
                                  <i class="fa fa-hashtag"></i> <?= e($_data['invoice_no']); ?>: <strong><?= $id; ?></strong>
                                </span>
                              </div>
                            </div>
                          </div>

                          <div class="modal-body">
                            <h4 class="section-title"><i class="fa fa-list-ul"></i> <?= e($_data['details_information']); ?></h4>

                            <div class="info-grid">
                              <div class="grid-col">
                                <div class="kv"><div class="k"><?= e($_data['add_new_form_field_text_6']); ?>:</div><div class="v"><?= $r_name; ?></div></div>
                                <div class="kv"><div class="k"><?= e($_data['add_new_form_field_text_1']); ?>:</div><div class="v"><?= $b_name; ?></div></div>
                                <div class="kv"><div class="k"><?= e($_data['add_new_form_field_text_3']); ?>:</div><div class="v"><?= $unit_no; ?></div></div>

                                <div class="kv">
                                  <div class="k"><?= e($_data['start_date']); ?>:</div>
                                  <div class="v"><span class="chip chip-start"><i class="fa fa-calendar-check-o"></i> <?= e($row['start_date']); ?></span></div>
                                </div>

                                <div class="kv">
                                  <div class="k"><?= e($_data['end_date']); ?>:</div>
                                  <div class="v"><span class="chip chip-end"><i class="fa fa-calendar-times-o"></i> <?= e($row['end_date']); ?></span></div>
                                </div>

                                <div class="kv">
                                  <div class="k"><?= e($_data['add_new_form_field_text_7']); ?>:</div>
                                  <div class="v">
                                    <span class="chip chip-money">
                                      <span class="sym"><?= $currency; ?></span><?= number_format($total_rent, 2); ?>
                                    </span>
                                  </div>
                                </div>
                              </div>

                              <div class="grid-col">
                                <div class="kv">
                                  <div class="k"><?= e($_data['add_new_form_field_text_15']); ?>:</div>
                                  <div class="v"><span class="chip chip-date"><i class="fa fa-calendar"></i> <?= e($row['issue_date']); ?></span></div>
                                </div>
                              </div>
                            </div>
                          </div>

                          <div class="modal-footer" style="display:flex;justify-content:flex-end;gap:8px;">
                            <button type="button" class="btn btn-default btn-pill" data-dismiss="modal">
                              <i class="fa fa-times"></i> Close
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>

                    <?php if ($balance > 0): ?>
                    <!-- Payment Modal (only when balance > 0) -->
                    <div id="payment_view_<?= $id; ?>" class="modal fade payment-modal" tabindex="-1" role="dialog" aria-hidden="true" aria-labelledby="paymentModalTitle_<?= $id; ?>">
                      <div class="modal-dialog">
                        <div class="modal-content">
                          <div class="modal-header fancy">
                            <button aria-label="Close" data-dismiss="modal" class="close" type="button">
                              <span aria-hidden="true"><i class="fa fa-close"></i></span>
                            </button>
                            <h3 id="paymentModalTitle_<?= $id; ?>" class="modal-title">
                              <i class="fa fa-credit-card"></i> <?= e($_data['rented_details']); ?>
                            </h3>
                          </div>

                          <div class="modal-body">
                            <div class="tenant-card">
                              <img src="<?= $image; ?>" alt="Tenant photo" class="avatar">
                              <div class="tenant-info">
                                <div class="tenant-name"><?= $r_name; ?></div>
                                <div class="tenant-balance">
                                  <span class="label">Balance:</span>
                                  <span class="chip"><span class="sym"><?= $currency; ?></span><?= number_format($balance, 2); ?></span>
                                </div>
                              </div>
                            </div>
                          </div>

                          <div class="modal-body">
                            <h4 class="section-title"><i class="fa fa-plus-circle"></i> Add Payment</h4>
                            <form action="<?= $add_payment_url ?>" method="post" id="frm_payment_<?= $id; ?>" novalidate>
                              <div class="form-group">
                                <label class="control-label">Balance Remaining</label>
                                <div class="input-group">
                                  <div class="input-group-addon"><?= $currency; ?></div>
                                  <input type="text" class="form-control" readonly value="<?= number_format($balance, 2); ?>">
                                </div>
                                <p class="help-block" style="color:#64748b;">
                                  This is the current outstanding amount for this service fee.
                                </p>
                              </div>

                              <div class="form-group has-feedback" id="amount_wrap_<?= $id; ?>">
                                <label class="control-label">Amount Paid <small class="muted">(max: <?= $currency . number_format($balance,2); ?>)</small></label>
                                <div class="input-group">
                                  <div class="input-group-addon"><?= $currency; ?></div>
                                  <input
                                    type="number"
                                    step="0.01"
                                    min="0.01"
                                    id="amount_paid_<?= $id; ?>"
                                    name="amount_paid"
                                    max="<?= $balance ?>"
                                    class="form-control"
                                    placeholder="0.00"
                                    required
                                    aria-describedby="amt_hint_<?= $id; ?>"
                                  />
                                </div>
                                <div class="inline-actions" style="margin-top:6px;">
                                  <button type="button" class="btn btn-link btn-xs" id="btn_full_<?= $id; ?>">
                                    <i class="fa fa-check-circle"></i> Pay full balance
                                  </button>
                                  <button type="button" class="btn btn-link btn-xs" id="btn_clear_<?= $id; ?>">
                                    <i class="fa fa-eraser"></i> Clear
                                  </button>
                                </div>
                                <div id="amt_hint_<?= $id; ?>" class="help-block" aria-live="polite"></div>
                                <div class="progress slim-progress" id="amt_progress_wrap_<?= $id; ?>" style="display:none;">
                                  <div class="progress-bar" id="amt_progress_<?= $id; ?>" role="progressbar" aria-valuemin="0" aria-valuemax="100"></div>
                                </div>
                              </div>

                              <input type="hidden" name="rent_id" value="<?= $id; ?>" />
                              <div class="text-right">
                                <button type="submit" class="btn btn-success" id="btn_submit_<?= $id; ?>">
                                  <i class="fa fa-floppy-o"></i> Save
                                </button>
                              </div>
                            </form>
                          </div>

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

                    <!-- Modal scripts (ONLY when balance > 0) -->
                    <script>
                      (function(){
                        var max     = parseFloat('<?= $balance ?>') || 0;
                        var $modal  = $('#payment_view_<?= $id; ?>');
                        var $form   = $('#frm_payment_<?= $id; ?>');
                        var $input  = $('#amount_paid_<?= $id; ?>');
                        var $wrap   = $('#amount_wrap_<?= $id; ?>');
                        var $hint   = $('#amt_hint_<?= $id; ?>');
                        var $progW  = $('#amt_progress_wrap_<?= $id; ?>');
                        var $prog   = $('#amt_progress_<?= $id; ?>');
                        var $btn    = $('#btn_submit_<?= $id; ?>');

                        function fmt(n){ return (isFinite(n) ? Number(n).toFixed(2) : '0.00'); }
                        function validate(){
                          var raw = ($input.val() || '').trim();
                          var val = parseFloat(raw);
                          $wrap.removeClass('has-error has-success');
                          $hint.text(''); $progW.hide();

                          if (!raw) { $btn.prop('disabled', true); return false; }
                          if (!isFinite(val) || val <= 0) {
                            $wrap.addClass('has-error'); $hint.text('Please enter a valid amount greater than 0.');
                            $btn.prop('disabled', true); return false;
                          }
                          if (max > 0 && val > max) {
                            $wrap.addClass('has-error'); $hint.text('Amount exceeds remaining balance (max: <?= $currency; ?>' + fmt(max) + ').');
                            $btn.prop('disabled', true); return false;
                          }
                          var remaining = max - (isFinite(val)?val:0);
                          $wrap.addClass('has-success');
                          $hint.html('You are paying <strong><?= $currency; ?>' + fmt(val) + '</strong>. Remaining after payment: <strong><?= $currency; ?>' + fmt(remaining) + '</strong>.');
                          var pct = Math.min(100, (val / max) * 100);
                          $progW.show(); $prog.css({ width: pct + '%' }).attr('aria-valuenow', Math.round(pct));

                          $btn.prop('disabled', false);
                          return true;
                        }
                        $input.on('input change', validate);
                        $('#btn_full_<?= $id; ?>').on('click', function(){ 
                          if (max > 0) { $input.val(fmt(max)); } 
                          else { $input.val(''); }
                          validate(); $input.focus(); 
                        });
                        $('#btn_clear_<?= $id; ?>').on('click', function(){ $input.val(''); validate(); $input.focus(); });
                        $modal.on('shown.bs.modal', function(){ setTimeout(function(){ $input.trigger('focus'); }, 120); validate(); });
                        $form.on('submit', function(e){ if (!validate()) { e.preventDefault(); return; } $btn.prop('disabled', true); });
                      })();
                    </script>
                    <?php endif; ?>

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

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

<script type="text/javascript">
  function deleteService(Id){
    let go = function(){
      window.location = '<?= WEB_URL; ?>service_fee/servicelist.php?action=delete&id=' + Id;
    }
    if (typeof sweetConfirmDelete === 'function') sweetConfirmDelete(go);
    else if (confirm('<?= addslashes($_data['delete_text']);?>?')) go();
  }

  $(document).ready(function() {
    setTimeout(function() {
      <?php if($msg == null){ ?>
        $("#me").fadeOut(300);
        $("#you").fadeOut(300);
      <?php } ?>
    }, 3000);

    // DataTables (keep newest first by ID)
    if ($.fn.DataTable) {
      $('#serviceTable').DataTable({
        pageLength: 10,
        order: [[0, 'desc']], // ID desc
        responsive: true,
        columnDefs: [
          { orderable: false, targets: [10] } // actions column
        ],
        language: {
          search: "Quick Search:",
          searchPlaceholder: "Type to filter…"
        }
      });
    }
  });
</script>
<?php include_once('../footer.php'); ?>
