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

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

// Role check
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['sales_manager', 'sales_executive'])) {
    echo "Access Denied";
    exit;
}

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

function build_url($params = []) {
    $query = array_merge($_GET, $params);
    foreach ($query as $k => $v) {
        if ($v === '' || $v === null) unset($query[$k]);
    }
    return '?' . http_build_query($query);
}

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

$today = date('Y-m-d');
$monthStart = date('Y-m-01');

if ($range === 'today') {
    $date1 = $today;
    $date2 = $today;
} elseif ($range === 'month') {
    $date1 = $monthStart;
    $date2 = $today;
}

$where = [];
$params = [];
$types  = '';

/* ============================
   SALES MANAGER FILTER
============================ */

$currentUserId = $_SESSION['user_id'];

// ðŸ”¹ If Sales Manager â†’ show own + his MR data
if ($_SESSION['role'] === 'sales_manager') {

    $where[] = "(b.created_by = ? 
        OR b.created_by IN (
            SELECT id FROM users WHERE manager_id = ?
        )
    )";

    $params[] = $currentUserId;
    $params[] = $currentUserId;
    $types .= "ii";
}

// ðŸ”¹ If Sales Executive â†’ only own data
if ($_SESSION['role'] === 'sales_executive') {

    $where[] = "b.created_by = ?";
    $params[] = $currentUserId;
    $types .= "i";
}

// only paid records
$where[] = "b.payment_status = 'paid'";

if ($search !== '') {
    $where[] = "(CAST(b.id AS CHAR) LIKE ? OR b.customer_name LIKE ? OR bi.product_name LIKE ?)";
    $like = "%{$search}%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types .= 'sss';
}

if ($date1 !== '') {
    $where[] = "DATE(b.created_at) >= ?";
    $params[] = $date1;
    $types .= 's';
}

if ($date2 !== '') {
    $where[] = "DATE(b.created_at) <= ?";
    $params[] = $date2;
    $types .= 's';
}

$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$sql = "
    SELECT
        b.id AS bill_no,
        b.created_at AS bill_date,
        b.customer_name,
        b.payment_status,
        b.created_by,
        u.name AS created_by_name,
        u.role AS created_by_role,
        bi.product_name,
        bi.qty,
        bi.price AS rate,
        bi.total AS amount
    FROM bills b
    LEFT JOIN users u ON u.id = b.created_by
    INNER JOIN bill_items bi ON bi.bill_id = b.id
    $whereSql
    ORDER BY b.created_at DESC, b.id DESC, bi.id DESC
";

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die('Query prepare failed: ' . $conn->error);
}

if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}

$stmt->execute();
$result = $stmt->get_result();

$rows = [];
$totalQty = 0;
$totalAmount = 0;
$billIds = [];

while ($row = $result->fetch_assoc()) {
    $rows[] = $row;
    $totalQty += (float)$row['qty'];
    $totalAmount += (float)$row['amount'];
    $billIds[$row['bill_no']] = true;
}

$stmt->close();
$totalBills = count($billIds);

// ðŸ”¥ ADD THIS CODE HERE
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    $filename = 'sold_products_' . date('Y-m-d_H-i-s') . '.xls';

    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Pragma: no-cache");
    header("Expires: 0");

    echo "<table border='1'>";
  echo "<tr>
        <th>Bill No</th>
        <th>Date</th>
        <th>Customer</th>
        <th>Created By</th>
        <th>Panel / Role</th>
        <th>Product</th>
        <th>Qty</th>
        <th>Rate</th>
        <th>Total</th>
      </tr>";

    foreach ($rows as $row) {
      echo "<tr>";
echo "<td>" . (int)$row['bill_no'] . "</td>";
echo "<td>" . date('Y-m-d', strtotime($row['bill_date'])) . "</td>";
echo "<td>" . e($row['customer_name']) . "</td>";
echo "<td>" . e($row['created_by_name'] ?? 'N/A') . "</td>";
echo "<td>" . e($row['created_by_role'] ?? 'N/A') . "</td>";
echo "<td>" . e($row['product_name']) . "</td>";
echo "<td>" . (float)$row['qty'] . "</td>";
echo "<td>" . number_format((float)$row['rate'], 2) . "</td>";
echo "<td>" . number_format((float)$row['amount'], 2) . "</td>";
echo "</tr>";
    }

    echo "</table>";
    exit;
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Sold Products</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">

  <style>
    body{
      background:#eef2f6;
      font-family:'Segoe UI',sans-serif;
    }

 .main-content {
  margin-left: 250px;
  position: relative;
  top: -60px;
  padding: 5px 30px; /* ðŸ”¥ reduce */
}

    .header-title{
      font-size:20px;
      font-weight:700;
      color:#0f172a;
      display:flex;
      align-items:center;
      gap:10px;
    }

    
    .header-title::before{
      content:"";
      width:10px;
      height:24px;
      border-radius:8px;
      background:#334155;
      display:inline-block;
    }

    .sub-title{
      color:#64748b;
      margin-top:6px;
      font-size:13px;
    }

    .card-soft{
      background:#fff;
      border-radius:16px;
      box-shadow:0 6px 22px rgba(15,23,42,.06);
      border:1px solid rgba(148,163,184,.18);
    }

    .filter-label{
      font-weight:700;
      color:#1e293b;
      font-size:14px;
      margin-bottom:8px;
    }

    .form-control, .form-select{
      border-radius:14px;
      border:1px solid #d8e0ea;
      padding:10px 12px;
      box-shadow:none !important;
      font-size: 13.5px;
    }

    .form-control:focus, .form-select:focus{
      border-color:#334155;
    }

    .btn-pill{
      border-radius:999px;
      padding:8px 14px;
      font-weight:700;
      border:1px solid transparent;
      font-size: 13px;
    }

    .btn-dark-pill{
      background:#334155;
      color:#fff;
    }

    .btn-dark-pill:hover{
      background:#1f2937;
      color:#fff;
    }

    .btn-light-pill{
      background:#fff;
      border-color:#d8e0ea;
      color:#334155;
    }

    .btn-light-pill:hover{
      background:#f8fafc;
      color:#0f172a;
    }

    .table-wrap{
      margin-top:10px;
    }

    .table-modern{
      border-collapse:separate;
      border-spacing:0 12px;
      width:100%;
    }

    .table-modern thead th{
      background:#334155;
      color:#fff;
      border:none;
      padding:10px 12px;
      font-weight:700;
      font-size:13px;
      white-space:nowrap;
    }

    .table-modern thead th:first-child{
      border-top-left-radius:14px;
      border-bottom-left-radius:14px;
    }

    .table-modern thead th:last-child{
      border-top-right-radius:14px;
      border-bottom-right-radius:14px;
      text-align:center;
    }

    .table-modern tbody tr{
      background:#fff;
      box-shadow:0 4px 14px rgba(15,23,42,.05);
      border-radius:14px;
      padding:10px 12px;   /* was 16px */
  font-size:13.5px;
      overflow:hidden;
    }

    .table-modern tbody td{
      background:#fff;
      padding:12px 16px;
      vertical-align:middle;
      border-top:1px solid #edf2f7;
      border-bottom:1px solid #edf2f7;
      font-size:14px;
      color:#0f172a;
      white-space:nowrap;
    }

    .table-modern tbody td:first-child{
      border-left:1px solid #edf2f7;
      border-top-left-radius:14px;
      border-bottom-left-radius:14px;
    }

    .table-modern tbody td:last-child{
      border-right:1px solid #edf2f7;
      border-top-right-radius:14px;
      border-bottom-right-radius:14px;
      text-align:center;
    }

    .icon-btn{
      width:34px;
      height:34px;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      border-radius:11px;
      background:#edf2f7;
      color:#334155;
      text-decoration:none;
      border:1px solid #dce3eb;
    }

    .icon-btn:hover{
      background:#e2e8f0;
      color:#0f172a;
    }

    .top-actions{
      display:flex;
      flex-wrap:wrap;
      gap:10px;
      align-items:center;
      justify-content:flex-end;
    }

    .badge-pill{
      background:#334155;
      color:#fff;
      border-radius:999px;
      padding:10px 16px;
      font-weight:700;
      display:inline-flex;
      align-items:center;
      gap:8px;
    }

    .count-badge{
      background:#334155;
      color:#fff;
      border-radius:999px;
      padding:8px 12px;
      font-weight:700;
      font-size: 12.5px;
    }

    .search-input{
      border-radius:14px;
      padding:12px 16px;
    }

    .empty-box{
      background:#fff;
      border:1px dashed #cbd5e1;
      border-radius:16px;
      padding:28px;
      text-align:center;
      color:#64748b;
      box-shadow:0 4px 14px rgba(15,23,42,.04);
    }

    @media (max-width: 992px){
      .main-content{
        margin-left:0;
        padding:16px;
      }
      .top-actions{
        justify-content:flex-start;
      }
    }
    /* ================= MOBILE PERFECT ================= */
@media (max-width:768px){

  html, body{
    overflow-x:hidden;
  }

  .main-content{
    margin-left:0 !important;
    padding:70px 10px 10px;
  }

  /* STACK FILTER */
  .row.g-3{
    flex-direction:column;
  }

  .col-lg-4,
  .col-lg-6{
    width:100%;
  }

  .top-actions{
    justify-content:flex-start;
  }

  /* 🔥 TABLE → CARD */
  .table-modern{
    border-spacing:0 12px;
  }

  .table-modern thead{
    display:none;
  }

  .table-modern,
  .table-modern tbody,
  .table-modern tr,
  .table-modern td{
    display:block;
    width:100%;
  }

  .table-modern tr{
    background:#fff;
    border-radius:16px;
    padding:12px;
    box-shadow:0 4px 12px rgba(0,0,0,0.05);
  }

  .table-modern td{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:8px 0;
    border:none;
    border-bottom:1px dashed #e5e7eb;
    font-size:13px;
  }

  .table-modern td:last-child{
    border-bottom:none;
  }

  /* 🔥 LABEL SHOW */
  .table-modern td::before{
    content:attr(data-label);
    font-size:11px;
    font-weight:700;
    color:#64748b;
    text-transform:uppercase;
  }

}

/* SMALL MOBILE */
@media (max-width:480px){

  .table-modern td{
    font-size:12px;
  }

  .table-modern td::before{
    font-size:10px;
  }

}
  </style>
</head>
<body>

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

<div class="main-content">
  <div class="container-fluid py-0">

    <div class="mb-3">
      <div class="header-title">Sold Products</div>
      <div class="sub-title">Filter bills by date range (Today / This Month) â€” including only paid records.</div>
    </div>

    <!-- FILTER BOX -->
    <div class="card-soft p-3 p-md-4 mb-3">
      <form method="get">
        <div class="row g-3 align-items-end">
          <div class="col-lg-4">
            <label class="filter-label">From</label>
            <input type="date" name="date1" class="form-control" value="<?php echo e($date1); ?>">
          </div>

          <div class="col-lg-4">
            <label class="filter-label">To</label>
            <input type="date" name="date2" class="form-control" value="<?php echo e($date2); ?>">
          </div>

          <div class="col-lg-4">
            <div class="d-flex flex-wrap gap-2">
              <button type="submit" name="range" value="today" class="btn btn-light-pill btn-pill">Today</button>
              <button type="submit" name="range" value="month" class="btn btn-light-pill btn-pill">This Month</button>
              <button type="submit" class="btn btn-dark-pill btn-pill">
                <i class="fa-solid fa-magnifying-glass me-2"></i>Search
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>

    <!-- SEARCH + ACTIONS -->
    <div class="card-soft p-3 p-md-4 mb-3">
      <form method="get" class="row g-3 align-items-center">
        <div class="col-lg-6">
          <input
            type="text"
            name="q"
            class="form-control search-input"
            placeholder="Search Bill No, Customer, Products"
            value="<?php echo e($search); ?>"
          >
        </div>

        <div class="col-lg-6">
          <div class="top-actions">
            <span class="badge-pill">
              <?php echo $range === 'today' ? 'Today' : ($range === 'month' ? 'This Month' : 'All Time'); ?>
            </span>

            <span class="count-badge"><?php echo (int)$totalBills; ?> bills</span>

            <a href="<?php echo e(build_url(['export' => 'excel'])); ?>" class="btn btn-light-pill btn-pill">
              <i class="fa-regular fa-file-excel me-2"></i>Export in Excel
            </a>
          </div>
        </div>

        <?php
          // preserve date filters when searching
          if ($date1 !== '') echo '<input type="hidden" name="date1" value="'.e($date1).'">';
          if ($date2 !== '') echo '<input type="hidden" name="date2" value="'.e($date2).'">';
          if ($range !== '') echo '<input type="hidden" name="range" value="'.e($range).'">';
        ?>
      </form>
    </div>

    <!-- TABLE -->
    <div class="table-wrap">
      <div class="table-responsive">
        <table class="table table-modern align-middle">
          <thead>
  <tr>
    <th>Bill No</th>
    <th>Date</th>
    <th>Customer</th>
    <th>Created By</th>
    <th>Panel / Role</th>
    <th>Products (unit price)</th>
    <th>Total</th>
    <th>View / Invoice</th>
  </tr>
</thead>
          <tbody>
            <?php if (!empty($rows)): ?>
              <?php foreach ($rows as $row): ?>
            <tr>
  <td data-label="Bill No"><?php echo (int)$row['bill_no']; ?></td>

  <td data-label="Date">
    <?php echo date('Y-m-d', strtotime($row['bill_date'])); ?>
  </td>

  <td data-label="Customer">
    <?php echo e($row['customer_name']); ?>
  </td>

  <td data-label="Created By">
    <?php echo e($row['created_by_name'] ?? 'N/A'); ?>
  </td>

  <td data-label="Panel / Role">
    <span class="badge bg-secondary">
      <?php echo e($row['created_by_role'] ?? 'N/A'); ?>
    </span>
  </td>

  <td data-label="Product">
    <?php echo e($row['product_name']); ?>
    <span class="text-muted">
      (<?php echo number_format((float)$row['rate'], 2); ?>)
    </span>
  </td>

  <td data-label="Total">
    <strong><?php echo number_format((float)$row['amount'], 2); ?></strong>
  </td>

  <td data-label="Invoice">
    <a href="view_bill.php?id=<?php echo (int)$row['bill_no']; ?>" class="icon-btn">
      <i class="fa-regular fa-file-lines"></i>
    </a>
  </td>
</tr>
              <?php endforeach; ?>
            <?php else: ?>
              <tr>
                <td colspan="8">
                  <div class="empty-box">No Data Found</div>
                </td>
              </tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

  </div>
</div>

</body>
</html>