<?php
require_once '../resource/sessions.php';
require_once '../master_functions.php';
require_once '../db/Config.php';

$db = new Config();
$conn = $db->getConnection();

$currentmonth = date('Y-m');
$sub_menu = 'dash';

function StockAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no';");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function FBAStockAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and sellable=1;");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function ReworkAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and sellable=2;");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function BGradeAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and sellable=3;");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function CGradeAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and sellable=4;");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function LiquidationAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and (sellable=3 or sellable=4);");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function DisposalStockAtHand() {
  global $conn;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where fba_shipped='no' and is_disposed='no' and sellable=5;");
    $stmt->execute();
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function PendingFBA() {
  global $conn, $currentmonth;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where (sellable=1 or sellable=2) and date_received like :m;");
    $stmt->execute([':m' => "%$currentmonth%"]);
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function Disposed() {
  global $conn, $currentmonth;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where sellable=5 and date_received like :m;");
    $stmt->execute([':m' => "%$currentmonth%"]);
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function QtyReturned() {
  global $conn, $currentmonth;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where date_received like :m;");
    $stmt->execute([':m' => "%$currentmonth%"]);
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
function LiquidationReturned() {
  global $conn, $currentmonth;
  $count = 0;
  try {
    $stmt = $conn->prepare("select count(*) total from process where date_received like :m and (sellable=3 or sellable=4 or sellable=2);");
    $stmt->execute([':m' => "%$currentmonth%"]);
    if ($row = $stmt->fetch()) $count = $row['total'];
  } catch (Exception $exc) { echo "Unexpected Error Occured"; }
  return $count;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Admin Dashboard</title>

  <?php require('../imports/importcss.php'); ?>
  <link rel="stylesheet" href="../assets/css/style.css">
  <link rel="stylesheet" href="assets/vendors/bootstrap-datepicker/bootstrap-datepicker.min.css">

  <style>
    /* ---- Cards polish ---- */
    .dashboard-card { border-radius: 14px; overflow: hidden; }
    .dashboard-card-header { font-weight: 800; letter-spacing: .02em; }

    /* ============================================================
       MONTHLY ACTIVITY: Make tiles fill almost entire card (no skinny)
       ============================================================ */
    .sales-activity .card-body{
      padding: 18px;
      /* make the grid naturally fill available space */
      display: flex;
    }
    .sales-activity .activity-grid{
      flex: 1 1 auto;
      width: 100%;
      display: grid;
      grid-template-columns: repeat(2, minmax(0, 1fr)); /* true 50/50 */
      gap: 16px;
      align-items: stretch;
      /* make rows equal height */
      grid-auto-rows: 1fr;
    }
    .sales-activity .so-inner-widget{
      width: 100%;
      height: 100%;
      border: 1px solid rgba(0,0,0,.08);
      border-radius: 16px;
      padding: 20px 18px;
      background: #fff;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center; /* centers vertically inside each tile */
      text-align: center;
    }
    .sales-activity .mobileicons{ margin-bottom: 10px !important; }
    .sales-activity .mobileicons i{ font-size: 38px; line-height: 1; display: inline-block; }
    .sales-activity .legend{
      line-height: 1.05;
      font-weight: 900;
      font-size: 2.2rem;
      margin-bottom: 6px;
    }
    .sales-activity .sales-qty{
      font-size: 0.8rem;
      letter-spacing: 0.08em;
      margin-bottom: 14px;
      opacity: 0.75;
      text-transform: uppercase;
    }
    .sales-activity .qty-label label{
      font-size: 0.78rem;
      letter-spacing: 0.06em;
      opacity: 0.9;
      margin: 0;
      line-height: 1.25;
      max-width: 280px;
    }
    .sales-activity .so-inner-widget-separator{ display:none !important; }

    /* On smaller widths, stack to 1 column so tiles stay big */
    @media (max-width: 991.98px){
      .sales-activity .activity-grid{ grid-template-columns: 1fr; }
      .sales-activity .so-inner-widget{ padding: 18px 16px; }
    }

    /* ---- Inventory Summary: clean flex rows ---- */
    .inventory-summary .inv-summary{
      display:flex; align-items:center; justify-content:space-between; gap:12px;
      padding: 10px 0; border-bottom: 1px solid rgba(0,0,0,.06);
    }
    .inventory-summary .inv-summary:last-child{ border-bottom:0; }
    .inventory-summary .inv-summary label{ margin:0; flex:1 1 auto; max-width:70%; line-height:1.2; }
    .inventory-summary .inv-summary .qty{ flex:0 0 auto; font-weight:900; font-size:1.45rem; line-height:1; }

    /* ---- Top Returned Items: grid + NO gray behind image ---- */
    .top-items-grid{
      display:grid;
      grid-template-columns: repeat(6, minmax(0,1fr));
      gap: 14px;
    }
    @media (max-width: 1199.98px){ .top-items-grid{ grid-template-columns: repeat(3, minmax(0,1fr)); } }
    @media (max-width: 575.98px){ .top-items-grid{ grid-template-columns: repeat(2, minmax(0,1fr)); } }

    .top-item{
      border: 1px solid rgba(0,0,0,.06);
      border-radius: 14px;
      padding: 14px;
      background: #fff;
      transition: transform .12s ease, box-shadow .12s ease;
      cursor: pointer; /* clickable card */
    }
    .top-item:hover{
      transform: translateY(-2px);
      box-shadow: 0 10px 22px rgba(0,0,0,.08);
    }

    .top-item .item-image{
      width: 100%;
      height: 120px;
      display:flex;
      align-items:center;
      justify-content:center;
      overflow:hidden;
      background: transparent;
      border-radius: 0;
      padding: 0;
      margin-bottom: 4px;
    }
    .top-item .item-image img{
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
      display:block;
      pointer-events: none; /* clicking image still triggers card click */
    }
    .top-item .name{
      margin-top: 10px;
      font-weight: 500;
    }
    .top-item .top-quantity{
      margin: 6px 0 0;
      font-weight: 900;
    }

    /* ---- RFR chart responsive ---- */
    .chart-wrap{ max-width: 420px; margin: 0 auto; }
    #returnChart{ max-width:100% !important; height:auto !important; }

    /* ---- Sexy modal tiles ---- */
    .stat-tile{
      background: #f9fafb;
      border: 1px solid rgba(0,0,0,.06);
      border-radius: 14px;
      padding: 14px 16px;
      text-align: center;
    }
    .stat-tile label{
      display:block;
      font-size: .7rem;
      letter-spacing: .08em;
      text-transform: uppercase;
      opacity: .65;
      margin-bottom: 6px;
    }
    .stat-tile span{
      font-size: 1.65rem;
      font-weight: 900;
      line-height: 1.1;
      display:block;
    }
    .stat-muted{ background: rgba(0,0,0,.035); }
    #modalItemImage{ max-height: 240px; object-fit: contain; }
  </style>
</head>

<body class="with-welcome-text">
<div class="container-scroller">
  <?php require("../sections/header.php") ?>

  <div class="container-fluid page-body-wrapper">
    <?php require("../sections/navbar.php") ?>

    <div class="main-panel">
      <div class="content-wrapper">
        <div class="row">
          <div class="col-sm-12">
            <div class="home-tab">

              <div class="d-sm-flex align-items-center justify-content-between border-bottom">
                <ul class="nav nav-tabs" role="tablist">
                  <li class="nav-item">
                    <a class="nav-link active ps-0" id="home-tab" data-bs-toggle="tab" href="#overview" role="tab" aria-controls="overview" aria-selected="true">Dashboard</a>
                  </li>
                  
                  
                </ul>
              </div>

              <div class="tab-content tab-content-basic">

                <!-- DASHBOARD -->
                <div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="overview">

                  <div class="row">
                    <div class="col-sm-12">
                      <div class="row dashboard-section">

                        <!-- Monthly Activity (2x2 grid that fills the card) -->
                        <div class="col-lg-8 col-md-8 col-sm-12 sales-activity">
                          <div class="card dashboard-card h-100">
                            <div class="card-header dashboard-card-header">Monthly Activity</div>
                            <div class="card-body">
                              <div class="activity-grid">

                                <div class="so-inner-widget">
                                  <div class="mobileicons"><i class="mdi mdi-gift ccolr1"></i></div>
                                  <div class="legend over-flow fw-light text-open" id="ab74264b2"><?= number_format(QtyReturned()) ?></div>
                                  <div class="sales-qty"><span class="font-xs text-muted">Units</span></div>
                                  <div class="qty-label">
                                    <label class="fw-light text-uppercase d-flex align-items-center justify-content-center gap-2">
                                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="icon icon-xs align-text-top me-1">
                                        <path d="M256 32c30.3 0 59.6 5.9 87.2 17.6 26.7 11.3 50.6 27.4 71.2 48s36.7 44.5 48 71.2c11.7 27.6 17.6 56.9 17.6 87.2s-5.9 59.6-17.6 87.2c-11.3 26.7-27.4 50.6-48 71.2s-44.5 36.7-71.2 48C315.6 474.1 286.3 480 256 480s-59.6-5.9-87.2-17.6c-26.7-11.3-50.6-27.4-71.2-48s-36.7-44.5-48-71.2C37.9 315.6 32 286.3 32 256s5.9-59.6 17.6-87.2c11.3-26.7 27.4-50.6 48-71.2s44.5-36.7 71.2-48C196.4 37.9 225.7 32 256 32m0-32C114.6 0 0 114.6 0 256s114.6 256 256 256 256-114.6 256-256S397.4 0 256 0z"></path>
                                        <path d="M223 336h-.1c-4.3 0-8.3-1.8-11.3-4.8l-62.5-64c-6.2-6.3-6.1-16.4.3-22.6 6.3-6.2 16.4-6.1 22.6.3l51.2 52.4 117.6-116.6c6.3-6.2 16.4-6.2 22.6.1 6.2 6.3 6.2 16.4-.1 22.6l-129 128c-3 2.9-7.1 4.6-11.3 4.6z"></path>
                                      </svg>
                                      Total Units Received
                                    </label>
                                  </div>
                                </div>

                                <div class="so-inner-widget">
                                  <div class="mobileicons"><i class="mdi mdi-truck-delivery ccolr2"></i></div>
                                  <div class="legend over-flow fw-light text-red" id="af5210f5f"><?= number_format(PendingFBA()) ?></div>
                                  <div class="sales-qty"><span class="font-xs text-muted">Units</span></div>
                                  <div class="qty-label">
                                    <label class="fw-light text-uppercase d-flex align-items-center justify-content-center gap-2">
                                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="icon icon-xs align-text-top me-1">
                                        <path d="M256 32c30.3 0 59.6 5.9 87.2 17.6 26.7 11.3 50.6 27.4 71.2 48s36.7 44.5 48 71.2c11.7 27.6 17.6 56.9 17.6 87.2s-5.9 59.6-17.6 87.2c-11.3 26.7-27.4 50.6-48 71.2s-44.5 36.7-71.2 48C315.6 474.1 286.3 480 256 480s-59.6-5.9-87.2-17.6c-26.7-11.3-50.6-27.4-71.2-48s-36.7-44.5-48-71.2C37.9 315.6 32 286.3 32 256s5.9-59.6 17.6-87.2c11.3-26.7 27.4-50.6 48-71.2s44.5-36.7 71.2-48C196.4 37.9 225.7 32 256 32m0-32C114.6 0 0 114.6 0 256s114.6 256 256 256 256-114.6 256-256S397.4 0 256 0z"></path>
                                        <path d="M369.4 204.1c0-3.7-2.2-7.1-5.6-8.8l-103.5-51.8c-2.7-1.4-6-1.4-8.7 0l-103.4 51.7c-3.5 1.7-5.7 5.3-5.7 9.2v103.3c0 3.7 2.1 7 5.4 8.7L247 366c2 2.3 5.1 3.5 8.2 3.3 1.8.1 3.5-.2 5.1-1L364 316.5c3.3-1.6 5.4-5 5.4-8.7V204.1z"></path>
                                      </svg>
                                      Sellable Units Received
                                    </label>
                                  </div>
                                </div>

                                <div class="so-inner-widget">
                                  <div class="mobileicons"><i class="mdi mdi-tanker-truck ccolr3"></i></div>
                                  <div class="legend over-flow fw-light text-success" id="aa471e1b2"><?= number_format(LiquidationReturned()) ?></div>
                                  <div class="sales-qty"><span class="font-xs text-muted">Units</span></div>
                                  <div class="qty-label">
                                    <label class="fw-light text-uppercase d-flex align-items-center justify-content-center gap-2">
                                      <svg id="Layer_2" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="icon icon-xs align-text-top me-1">
                                        <g id="Layer_1-2">
                                          <path d="M437 75C388.7 26.6 324.4 0 256 0S123.3 26.6 75 75C26.6 123.3 0 187.6 0 256s26.6 132.7 75 181c48.4 48.4 112.6 75 181 75s132.7-26.6 181-75c48.4-48.4 75-112.6 75-181s-26.6-132.7-75-181zm-28.3 333.8c-40.8 40.8-95 63.3-152.7 63.3s-111.9-22.5-152.7-63.3S40 313.8 40 256.1s22.5-111.9 63.3-152.7c40.8-40.8 95-63.3 152.7-63.3s111.9 22.5 152.7 63.3c40.8 40.8 63.3 95 63.3 152.7S449.5 368 408.7 408.8z"></path>
                                          <path d="M256.1 224.9c-17.3 0-31.2 14-31.2 31.2s14 31.2 31.2 31.2 31.2-14 31.2-31.2-14-31.2-31.2-31.2zM135.7 224.9c-17.3 0-31.2 14-31.2 31.2s14 31.2 31.2 31.2 31.2-14 31.2-31.2-14-31.2-31.2-31.2zM376.5 224.9c-17.3 0-31.2 14-31.2 31.2s14 31.2 31.2 31.2 31.2-14 31.2-31.2-14-31.2-31.2-31.2z"></path>
                                        </g>
                                      </svg>
                                      Units Needs Rework
                                    </label>
                                  </div>
                                </div>

                                <div class="so-inner-widget">
                                  <div class="mobileicons"><i class="mdi mdi-invoice ccolr4"></i></div>
                                  <div class="legend over-flow fw-light text-parshipped" id="a6f9c8d99"><?= number_format(Disposed()) ?></div>
                                  <div class="sales-qty"><span class="font-xs text-muted">Units</span></div>
                                  <div class="qty-label">
                                    <label class="fw-light text-uppercase d-flex align-items-center justify-content-center gap-2">
                                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" class="icon icon-xs align-text-top me-1">
                                        <path d="M256 32c30.3 0 59.6 5.9 87.2 17.6 26.7 11.3 50.6 27.4 71.2 48s36.7 44.5 48 71.2c11.7 27.6 17.6 56.9 17.6 87.2s-5.9 59.6-17.6 87.2c-11.3 26.7-27.4 50.6-48 71.2s-44.5 36.7-71.2 48C315.6 474.1 286.3 480 256 480s-59.6-5.9-87.2-17.6c-26.7-11.3-50.6-27.4-71.2-48s-36.7-44.5-48-71.2C37.9 315.6 32 286.3 32 256s5.9-59.6 17.6-87.2c11.3-26.7-27.4 50.6-48 71.2s-44.5 36.7-71.2 48C196.4 37.9 225.7 32 256 32m0-32C114.6 0 0 114.6 0 256s114.6 256 256 256 256-114.6 256-256S397.4 0 256 0z"></path>
                                        <path d="M255 160l65 65v119c0 4.4-3.6 8-8 8H200c-4.4 0-8-3.6-8-8V168c0-4.4 3.6-8 8-8h55m0-20h-55c-15.4 0-28 12.6-28 28v176c0 15.4 12.6 28 28 28h112c15.4 0 28-12.6 28-28V225c0-5.3-2.1-10.4-5.9-14.1l-65-65c-3.7-3.8-8.8-5.9-14.1-5.9zm33 180h-64"></path>
                                      </svg>
                                      Unsellable Units Received
                                    </label>
                                  </div>
                                </div>

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

                        <!-- Inventory Summary -->
                        <div class="col-lg-4 col-md-4 col-sm-12 inventory-summary">
                          <div class="card dashboard-card">
                            <div class="card-header dashboard-card-header">Inventory Summary</div>
                            <div class="card-body">
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity In Warehouse</label>
                                <div class="qty text-plain"><?= number_format(StockAtHand()) ?></div>
                              </div>
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity Pending FBA</label>
                                <div class="qty text-plain"><?= number_format(FBAStockAtHand()) ?></div>
                              </div>
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity Needs Inserts</label>
                                <div class="qty text-plain"><?= number_format(ReworkAtHand()) ?></div>
                              </div>
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity Needs New Packaging</label>
                                <div class="qty text-plain"><?= number_format(BGradeAtHand()) ?></div>
                              </div>
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity Needs Insert & Packaging</label>
                                <div class="qty text-plain"><?= number_format(CGradeAtHand()) ?></div>
                              </div>
                              <div class="inv-summary">
                                <label class="text-uppercase fw-light font-small text-void">Quantity Pending Disposal</label>
                                <div class="qty text-plain"><?= number_format(DisposalStockAtHand()) ?></div>
                              </div>
                            </div>
                          </div>
                        </div>

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

                  <!-- Top Returned Items -->
                  <div class="row">
                    <div class="col-lg-12 col-md-12 col-sm-12">
                      <div class="card dashboard-card placeholder-container">
                        <div class="card-header dashboard-card-header d-flex align-items-center justify-content-between">
                          Top Returned Items
                          <div class="cursor-pointer dashboard-daterange-picker">
                            <div end_date="Sun Jun 30 2024 23:59:59 GMT+0530 (India Standard Time)"
                                 start_date="Sat Jun 01 2024 00:00:00 GMT+0530 (India Standard Time)"
                                 id="ember313" class="zf-daterange-picker ember-view">
                              <span class="caret"></span>
                            </div>
                          </div>
                        </div>

                        <div class="card-body">
                          <div class="top-items-grid">
                            <?php
                            $query = "SELECT 
                                count(*) AS totalreturn,
                                process.fnsku,
                                MIN(process.lpn) AS `lpn`,
                                MIN(catalog.`product-name`) AS `product-name`,
                                MIN(catalog.Image) AS Image
                              FROM `process` 
                              LEFT JOIN catalog ON catalog.fnsku = process.fnsku 
                              WHERE process.date_received LIKE '%$currentmonth%' 
                              GROUP BY process.fnsku
                              ORDER BY totalreturn DESC 
                              LIMIT 6;";
                            $stmt = $conn->prepare($query);
                            $stmt->execute();

                            while ($row = $stmt->fetch()) {
                              $img = !empty($row['Image']) ? $row['Image'] : '../assets/images/placeholder.png';
                              $productName = $row['product-name'] ?? 'Unknown Item';
                              $fnsku = $row['fnsku'] ?? '';
                              $totalreturn = (int)($row['totalreturn'] ?? 0);
                            ?>
                              <!-- Clicking the CARD opens modal now -->
                              <div class="top-item text-center open-item-modal-card"
                                   role="button"
                                   tabindex="0"
                                   data-fnsku="<?= htmlspecialchars($fnsku) ?>"
                                   data-product="<?= htmlspecialchars($productName) ?>"
                                   data-image="<?= htmlspecialchars($img) ?>"
                                   data-returns="<?= htmlspecialchars((string)$totalreturn) ?>">
                                <div class="item-image">
                                  <img src="<?= htmlspecialchars($img) ?>" alt="Item">
                                </div>

                                <div class="pt-2 over-flow fw-light text-void text-truncate name">
                                  <?= htmlspecialchars($productName) ?>
                                </div>

                                <h4 class="top-quantity text-plain">
                                  <?= number_format($totalreturn) ?><span class="fw-light"> Units</span>
                                </h4>
                              </div>
                            <?php } ?>
                          </div>
                        </div>

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

                  <br>

                  <!-- Reasons For Return -->
                  <div class="row">
                    <div class="col-lg-12 col-md-12 col-sm-12">
                      <div class="card dashboard-card">
                        <div class="card-header dashboard-card-header">Reasons For Return (RFR)</div>

                        <div class="row product-details card-body align-items-center">
                          <div class="col-lg-7 col-md-7 col-sm-12 total-summary">
                            <table class="table table-striped table-bordered">
                              <thead>
                                <tr>
                                  <th>Reason</th>
                                  <th class="text-end">Total Returns</th>
                                </tr>
                              </thead>
                              <tbody>
                              <?php
                                $query = "SELECT count(*) totalreturn, reason FROM `process`
                                          WHERE process.date_received LIKE '%$currentmonth%' and process.reason != 'No Data'
                                          GROUP BY reason ORDER BY totalreturn DESC;";
                                $stmt = $conn->prepare($query);
                                $stmt->execute();
                                while ($row = $stmt->fetch()) {
                                  echo "<tr>";
                                  echo "<td>" . htmlspecialchars(str_replace('_', ' ', $row['reason'])) . "</td>";
                                  echo "<td class='text-end'>" . number_format($row['totalreturn']) . "</td>";
                                  echo "</tr>";
                                }
                              ?>
                              </tbody>
                            </table>
                          </div>

                          <div class="col-lg-5 col-md-5 col-sm-12 text-center">
                            <label class="fw-light font-large text-void mb-0 w-75 text-truncate">
                              <span id="affbf1335">RFR</span>
                            </label>

                            <div class="pt-3 chart-wrap">
                              <?php
                              $query = "SELECT count(*) as totalreturn, reason FROM `process`
                                        WHERE process.date_received LIKE '%$currentmonth%' and process.reason != 'No Data'
                                        GROUP BY reason ORDER BY totalreturn DESC;";
                              $stmt = $conn->prepare($query);
                              $stmt->execute();

                              $reasons = [];
                              $total_returns = [];
                              while ($row = $stmt->fetch()) {
                                $reasons[] = str_replace('_', ' ', $row['reason']);
                                $total_returns[] = (int)$row['totalreturn'];
                              }
                              ?>
                              <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
                              <canvas id="returnChart" width="400" height="400"></canvas>
                              <script>
                                var ctx = document.getElementById('returnChart').getContext('2d');
                                new Chart(ctx, {
                                  type: 'pie',
                                  data: {
                                    labels: <?php echo json_encode($reasons); ?>,
                                    datasets: [{
                                      data: <?php echo json_encode($total_returns); ?>,
                                      borderWidth: 1
                                    }]
                                  },
                                  options: {
                                    responsive: true,
                                    plugins: { legend: { position: 'top' } }
                                  }
                                });
                              </script>
                            </div>
                          </div>

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

                </div>

                <!-- GETTING STARTED -->
                <div class="tab-pane fade" id="started" role="tabpanel" aria-labelledby="started">
                  <div style="position: relative; padding-bottom: 56.25%; height: 0;">
                    <iframe src="https://www.loom.com/embed/cb400dc3cd8d49b29f160159e3a99019?sid=1bfd38be-2607-43c6-ad13-ed8881d80562"
                            frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen
                            style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></iframe>
                  </div>
                </div>

                <!-- UPDATES -->
                <div class="tab-pane fade" id="more" role="tabpanel" aria-labelledby="more">
                  <div class="row">
                    <div class="row flex-grow">
                      <div class="col-md-12 col-lg-12 grid-margin stretch-card">
                        <div class="card card-rounded">
                          <div class="card-body card-rounded">
                            <h4 class="card-title card-title-dash">Updates</h4>
                            <div class="list align-items-center border-bottom py-2">
                              <div class="wrapper w-100">
                                <p class="mb-2 fw-medium">Portal Completed</p>
                                <div class="d-flex justify-content-between align-items-center">
                                  <div class="d-flex align-items-center">
                                    <i class="mdi mdi-calendar text-muted me-1"></i>
                                    <p class="mb-0 text-small text-muted">February 09, 2026</p>
                                  </div>
                                </div>
                              </div>
                            </div>

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

              </div><!-- /tab-content -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </div><!-- /container -->

  <!-- SEXY ITEM MODAL -->
  <div class="modal fade" id="itemDetailModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
      <div class="modal-content rounded-4 shadow-lg">

        <div class="modal-header border-0 pb-0">
          <div class="w-100">
            <div class="d-flex align-items-start justify-content-between gap-3">
              <div>
                <h5 class="modal-title fw-bold mb-1" id="itemModalTitle">Item Summary</h5>
                <div class="small text-muted">Current month summary (<?= htmlspecialchars($currentmonth) ?>)</div>
              </div>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
          </div>
        </div>

        <div class="modal-body pt-3">
          <div class="row g-4 align-items-start">

            <div class="col-md-4 text-center">
              <img id="modalItemImage" src="" class="img-fluid rounded-3 mb-3" alt="Item">
              <div class="small text-muted text-truncate" id="modalFnsku"></div>
            </div>

            <div class="col-md-8">
              <div class="row g-3">
                <div class="col-6">
                  <div class="stat-tile">
                    <label>Total Returned</label>
                    <span id="statTotalReturned">—</span>
                  </div>
                </div>

                <div class="col-6">
                  <div class="stat-tile">
                    <label>Sellable Units</label>
                    <span id="statSellable">—</span>
                  </div>
                </div>

                <div class="col-6">
                  <div class="stat-tile">
                    <label>Rework Units</label>
                    <span id="statRework">—</span>
                  </div>
                </div>

                <div class="col-6">
                  <div class="stat-tile">
                    <label>Liquidation Units</label>
                    <span id="statLiquidation">—</span>
                  </div>
                </div>

                <div class="col-12">
                  <div class="stat-tile stat-muted">
                    <label>Unsellable / Disposal</label>
                    <span id="statDisposed">—</span>
                  </div>
                </div>

              </div>

            </div>

          </div>
        </div>

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

  <?php require("../imports/importjs.php") ?>

  <script>
    document.addEventListener('DOMContentLoaded', function () {
      const modalEl = document.getElementById('itemDetailModal');
      if (!modalEl || typeof bootstrap === 'undefined') return;

      const modal = new bootstrap.Modal(modalEl, { backdrop: true, keyboard: true });

      function setLoadingState() {
        document.getElementById('statTotalReturned').innerText = '…';
        document.getElementById('statSellable').innerText = '…';
        document.getElementById('statRework').innerText = '…';
        document.getElementById('statLiquidation').innerText = '…';
        document.getElementById('statDisposed').innerText = '…';
      }

      async function loadSummary(fnsku) {
        const url = `ajax/get_item_monthly_summary.php?fnsku=${encodeURIComponent(fnsku)}`;
        const res = await fetch(url, { cache: 'no-store' });
        if (!res.ok) throw new Error('Failed to load summary');
        return await res.json();
      }

      function openModalFromCard(cardEl) {
        const fnsku = cardEl.dataset.fnsku || '';
        const product = cardEl.dataset.product || 'Item Summary';
        const image = cardEl.dataset.image || '';
        document.getElementById('modalItemImage').src = image;
        document.getElementById('itemModalTitle').innerText = product;
        document.getElementById('modalFnsku').innerText = fnsku ? `FNSKU: ${fnsku}` : '';

        setLoadingState();
        modal.show();

        if (!fnsku) {
          document.getElementById('statTotalReturned').innerText = '0';
          document.getElementById('statSellable').innerText = '0';
          document.getElementById('statRework').innerText = '0';
          document.getElementById('statLiquidation').innerText = '0';
          document.getElementById('statDisposed').innerText = '0';
          return;
        }

        loadSummary(fnsku)
          .then(data => {
            document.getElementById('statTotalReturned').innerText = data.total ?? 0;
            document.getElementById('statSellable').innerText = data.sellable ?? 0;
            document.getElementById('statRework').innerText = data.rework ?? 0;
            document.getElementById('statLiquidation').innerText = data.liquidation ?? 0;
            document.getElementById('statDisposed').innerText = data.disposed ?? 0;
          })
          .catch(e => {
            document.getElementById('statTotalReturned').innerText = '—';
            document.getElementById('statSellable').innerText = '—';
            document.getElementById('statRework').innerText = '—';
            document.getElementById('statLiquidation').innerText = '—';
            document.getElementById('statDisposed').innerText = '—';
            console.error(e);
          });
      }

      // Click anywhere on the Top Returned Item card
      document.querySelectorAll('.open-item-modal-card').forEach(card => {
        card.addEventListener('click', function () {
          openModalFromCard(this);
        });

        // Keyboard accessibility (Enter/Space)
        card.addEventListener('keydown', function (e) {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            openModalFromCard(this);
          }
        });
      });
    });
  </script>

</body>
</html>
