<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

function e($v){ return htmlspecialchars($v ?? '', ENT_QUOTES); }

$user_id = $_SESSION['user_id'];
$role    = $_SESSION['role']; // 🔥 IMPORTANT

$search = trim($_GET['q'] ?? '');
$date1  = $_GET['date1'] ?? '';
$date2  = $_GET['date2'] ?? '';

/* =========================
   ROLE BASED FILTER
========================= */
if ($role === 'medical_representative') {
    $where = "WHERE b.mr_id = '$user_id'"; // ✅ only own bills
} else {
    $where = "WHERE 1"; // admin / manager
}

/* =========================
   SEARCH FILTER
========================= */
if ($search !== '') {
    $searchEsc = $conn->real_escape_string($search);
    $where .= " AND (b.customer_name LIKE '%$searchEsc%' OR CAST(b.id AS CHAR) LIKE '%$searchEsc%')";
}

/* =========================
   DATE FILTER
========================= */
if (!empty($date1) && !empty($date2)) {
    $date1Esc = $conn->real_escape_string($date1);
    $date2Esc = $conn->real_escape_string($date2);
    $where .= " AND DATE(b.created_at) BETWEEN '$date1Esc' AND '$date2Esc'";
}

/* =========================
   QUERY
========================= */
$result = $conn->query("
    SELECT 
        b.id,
        b.customer_name,
        b.created_at,
        b.total_amount,
        b.payment_status,
        COALESCE(pi.product_name, '') AS product_name
    FROM bills b
    LEFT JOIN (
        SELECT 
            bill_id,
            GROUP_CONCAT(product_name SEPARATOR ', ') AS product_name
        FROM bill_items
        GROUP BY bill_id
    ) pi ON pi.bill_id = b.id
    $where
    ORDER BY b.id DESC
");

/* =========================
   SUMMARY
========================= */
$billCount = 0;
$totalAmount = 0.00;

if ($result && $result->num_rows > 0) {
    $billCount = $result->num_rows;
    while ($tmp = $result->fetch_assoc()) {
        $totalAmount += (float)($tmp['total_amount'] ?? 0);
    }
    $result->data_seek(0);
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<title>Bill History</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

<style>
:root{
  --accent:#2C3E50;
  --accent-ink:#ffffff;
  --ink:#0f172a;
  --muted:#6b7280;
  --stroke:#e3e6ef;
  --bg:#f7f9fb;
  --card-bg:#ffffff;
}

*{ box-sizing:border-box; }
html,body{ margin:0; padding:0; height:100%; }
body{
  font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
  background:var(--bg);
  color:var(--ink);
  -webkit-font-smoothing:antialiased;
  -moz-osx-font-smoothing:grayscale;
}

.container{
  margin-left:260px;
   padding:40px 20px 20px;
}

.page-wrap{
  max-width:1240px;
  margin:0 auto;
}

.title-wrap{
  margin:6px 0 18px;
}

.title{
  font-weight:800;
  font-size:22px;
  color:#000;
  display:flex;
  align-items:center;
  gap:8px;
  margin:0;
}

.title::before{
  content:"";
  width:6px;
  height:20px;
  border-radius:6px;
  background:#334155;
  box-shadow:0 8px 18px rgba(16,24,40,.15);
}

.subtitle{
  color:var(--muted);
  margin-top:4px;
  font-size:13px;
}

.cardx{
  background:#fff;
  backdrop-filter:blur(6px);
 border:1px solid var(--stroke);
  border-radius:14px;
box-shadow:0 8px 24px rgba(2,6,23,.08);
}

.cardx.pad{
  padding:14px;
}

.toolbar{
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:8px 10px 2px;
  gap:8px;
  flex-wrap:wrap;
}

.toolbar-left,
.toolbar-right{
  display:flex;
  gap:10px;
  align-items:center;
  flex-wrap:wrap;
}

.pill{
  background:#334155;
  color:var(--accent-ink);
  padding:5px 10px;
  border-radius:999px;
  font-size:11px;
  font-weight:700;
  box-shadow:0 4px 10px rgba(44,62,80,.10);
}

.input{
  width:100%;
  border:1px solid var(--stroke);
  border-radius:10px;
  padding:9px 12px;
  outline:none;
  transition:box-shadow .18s,border-color .18s;
  background:#fff;
  font-size:13px;
}

.input:focus{
  border-color:var(--accent);
  box-shadow:0 0 0 4px rgba(44,62,80,.09);
}

.table-card{
  padding:8px 10px 10px;
  overflow:visible;
  margin-top:12px;
}

.thead{
  position:sticky;
  top:0;
  z-index:1;
  background:#334155;
  color:#fff;
  border-radius:10px;
  padding:8px 10px;
  font-size:13px;
  display:grid;
  align-items:center;
  box-shadow:0 8px 18px rgba(16,24,40,.08);
  grid-template-columns: 70px 120px 1.5fr 1.5fr 100px 100px;
}

.tbody{
  padding:8px 6px 12px;
}

.row{
  display:grid;
  align-items:center;
  gap:10px;
  border-radius:8px;
  margin:6px 0;
  padding:8px;
  background:var(--card-bg);
  border:1px solid #eef1f6;
  transition:transform .12s ease, box-shadow .12s ease;
  border-radius:8px;
  grid-template-columns: 70px 120px 1.5fr 1.5fr 100px 100px;
}
.row:hover{
  transform:translateY(-1px);
  box-shadow:0 8px 20px rgba(16,24,40,.05);
}

.cell-head{
  font-weight:700;
}

.cell-text{
  font-weight:600;
  color:#111827;
  font-size:13px;
}

.text-right{ text-align:right; }
.text-center{ text-align:center; }

.badge{
  padding:5px 8px;
  border-radius:999px;
  font-size:11px;
  font-weight:700;
  display:inline-block;
  min-width:72px;
  text-align:center;
}

.paid{ background:#334155; color:#fff; }
.unpaid{  background:#334155; color:#fff; }
.advance{  background:#334155; color:#fff; }

.btn-filter{
  background: #334155;
  color:#fff;
  padding:8px 14px;
   font-size:13px;
  border-radius:999px;
  border:none;
  font-weight:700;
  display:flex;
  align-items:center;
  gap:8px;
  cursor:pointer;
  box-shadow:0 4px 12px rgba(0,0,0,0.15);
  transition:all .2s ease;
}

.btn-filter:hover{
  transform:translateY(-1px);
  box-shadow:0 6px 16px rgba(0,0,0,0.2);
}

.btn-reset{
  background:#fff;
  color:#0f172a;
  padding:8px 14px;
  font-size:13px;
  border-radius:999px;
  border:1px solid #e2e8f0;
  font-weight:700;
  display:flex;
  align-items:center;
  gap:8px;
  text-decoration:none;
  transition:all .2s ease;
}

.btn-reset:hover{
  background:#f1f5f9;
  transform:translateY(-1px);
}

.empty{
  text-align:center;
  padding:20px;
  color:var(--muted);
}

@media (max-width: 992px){
  .container{ padding-inline:12px; margin-left:0; }
  .thead{ display:none; }
  .row{ display:block; padding:12px; }
  .row + .row{ margin-top:12px; }
  .row > div{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:8px 0;
    border-bottom:1px dashed #f1f5f9;
    gap:10px;
  }
  .row > div:last-child{ border-bottom:0; }
  .row > div:before{
    content:attr(data-label);
    font-weight:700;
    color:var(--muted);
    margin-right:8px;
    display:inline-block;
    width:45%;
    font-size:0.92rem;
    text-align:left;
  }
  .row > div > .value{
    width:55%;
    text-align:right;
    word-break:break-word;
  }
}

@media (max-width: 420px){
  .row > div:before{ width:40%; font-size:13px; }
  .row > div > .value{ font-size:13px; }
}
/* ================= MOBILE IMPROVEMENT ================= */
@media (max-width: 768px){

    /* FULL WIDTH */
    .container{
        margin-left:0 !important;
        padding:10px;
    }

    .page-wrap{
        max-width:100%;
    }

    /* FILTER BAR FIX */
    .toolbar{
        flex-direction:column;
        align-items:stretch;
        gap:10px;
    }

    .toolbar-left{
        flex-direction:column;
        width:100%;
        gap:8px;
    }

    .toolbar-left input{
        width:100% !important;
    }

    .toolbar-left span{
        display:none; /* remove "to" gap */
    }

    /* BUTTON GROUP */
    .toolbar-left > div{
        flex-direction:column;
        width:100%;
        gap:8px;
    }

    .btn-filter,
    .btn-reset{
        width:100%;
        justify-content:center;
    }

    /* COUNT */
    .toolbar-right{
        width:100%;
        justify-content:flex-start;
    }

    /* CARD SPACING */
    .row{
        padding:12px;
        border-radius:12px;
    }

    /* TEXT IMPROVE */
    .row > div{
        padding:10px 0;
    }

    .row > div:before{
        font-size:13px;
        color:#475569;
    }

    .row .value{
        font-size:13px;
        font-weight:600;
    }

    /* TITLE */
    .title{
        font-size:18px;
    }

    .subtitle{
        font-size:12px;
    }
}
</style>
</head>

<body>

<?php include 'salesexecutivesidebar.php'; ?>
<?php include '../header.php'; ?>

<article class="content" id="company-ui">
  <div class="container">
    <div class="page-wrap">

      <div class="title-wrap">
        <h3 class="title">Bill History</h3>
        <div class="subtitle">Search bills by customer name or bill ID.</div>
      </div>

     <div class="cardx pad" style="margin-top:12px;">
  <form class="toolbar" method="get" id="filterForm">
    <div class="toolbar-left" style="display:flex; gap:10px; align-items:center; flex-wrap:wrap;">
      <input
        type="search"
        id="quickSearch"
        name="q"
        class="input"
        placeholder="Search Bill No, Customer"
        style="width:300px;"
        value="<?php echo e($search); ?>"
      >

      <input
        type="date"
        id="date1"
        name="date1"
        class="input"
        style="width:170px;"
        value="<?php echo e($date1); ?>"
      >

      <span style="font-weight:700; color:#000" >to</span>

      <input
        type="date"
        id="date2"
        name="date2"
        class="input"
        style="width:170px;"
        value="<?php echo e($date2); ?>"
      >

    <div style="display:flex; gap:10px; align-items:center;">
  
  <button type="submit" class="btn btn-filter">
    <i class="fa fa-filter"></i> Filter
  </button>

  <a href="bill_history.php" class="btn btn-reset">
    <i class="fa fa-rotate-left"></i> Reset
  </a>

</div>
    </div>

    <div class="toolbar-right">
      <span class="pill" id="count-pill"><?php echo $billCount; ?> bills</span>
    </div>
  </form>
</div>
      </div>

      <div class="cardx table-card">
       <div class="thead" role="rowgroup">
  <div class="cell-head text-center">ID</div>
   <div class="cell-head text-center">Product</div>
    <div class="cell-head text-center">Customer</div>
  <div class="cell-head text-center">Date</div>
  <div class="cell-head text-right">Total</div>
  <div class="cell-head text-center">Payment</div>
</div>
        <div class="tbody" id="listBody">
          <?php if ($result && $result->num_rows > 0): ?>
            <?php while($row = $result->fetch_assoc()): ?>
              <?php
                $status = strtolower(trim($row['payment_status'] ?? ''));
                $cls = ($status === 'paid') ? 'paid' : (($status === 'unpaid') ? 'unpaid' : 'advance');
                $customer = $row['customer_name'] ?: 'N/A';
                $total = (float)($row['total_amount'] ?? 0);
              ?>
 
             <div class="row" role="row">
  <div class="cell-text text-center" data-label="ID">
    <span class="value"><?php echo e($row['id']); ?></span>
  </div>

   <div class="cell-text text-center" data-label="Product">
    <span class="value"><?php echo e($row['product_name'] ?? 'N/A'); ?></span>
  </div>

 <div class="cell-text text-center" data-label="Customer">
    <span class="value"><?php echo e($customer); ?></span>
  </div>

  <div class="cell-text text-center" data-label="Date">
    <span class="value"><?php echo date('Y-m-d', strtotime($row['created_at'])); ?></span>
  </div>

 

 

  <div class="cell-text text-right" data-label="Total">
    <span class="value">₹ <?php echo number_format($total, 2, '.', ','); ?></span>
  </div>

  <div class="cell-text text-center" data-label="Payment">
    <span class="badge <?php echo $cls; ?>">
      <?php echo strtoupper($status ?: 'N/A'); ?>
    </span>
  </div>
</div>
            <?php endwhile; ?>
          <?php else: ?>
            <div class="empty">
              <?php echo $search !== '' ? 'No bills found for the selected search.' : 'No bills found.'; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

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

<script>
function pad(n){ return n<10 ? '0'+n : n; }

function formatDate(d){
  return d.getFullYear()+'-'+pad(d.getMonth()+1)+'-'+pad(d.getDate());
}

function setToday(){
  const t = new Date();
  const d1 = document.getElementById('date1');
  const d2 = document.getElementById('date2');
  if (d1) d1.value = formatDate(t);
  if (d2) d2.value = formatDate(t);
}

function setThisMonth(){
  const now = new Date();
  const first = new Date(now.getFullYear(), now.getMonth(), 1);
  const last = new Date(now.getFullYear(), now.getMonth()+1, 0);

  const d1 = document.getElementById('date1');
  const d2 = document.getElementById('date2');
  if (d1) d1.value = formatDate(first);
  if (d2) d2.value = formatDate(last);
}
</script>

<script>
const searchInput = document.getElementById('quickSearch');

searchInput.addEventListener('keyup', function() {
  const value = this.value.toLowerCase();
  const rows = document.querySelectorAll('#listBody .row');

  let visibleCount = 0;

  rows.forEach(row => {
    const text = row.innerText.toLowerCase();

    if (text.includes(value)) {
      row.style.display = '';
      visibleCount++;
    } else {
      row.style.display = 'none';
    }
  });

  // update count
  document.getElementById('count-pill').innerText = visibleCount + ' bills';
});
</script>

</body>
</html>