<?php

if (session_status() === PHP_SESSION_NONE) session_start();

if (empty($_SESSION['login'])) {
  header('Location: ?page=login');
  exit;
}

// Allow: usertype=RE OR permission array has RE
$isResellerByType   = (!empty($_SESSION['usertype']) && $_SESSION['usertype'] === 'RE');
$isResellerByAccess = (!empty($_SESSION['useraccess']) && isset($_SESSION['useraccess']['RE']));

if (!$isResellerByType && !$isResellerByAccess) {
  header('Location: ?page=access-denied');
  exit;
}

$id = $_SESSION['userid'];


$totalCustomer         = (int)$obj->Total_Count("re_tbl_agent", "entry_by=$id");
$totalActiveCustomer   = (int)$obj->Total_Count("re_tbl_agent", "ag_status=1 AND entry_by=$id");
$totalInactiveCustomer = (int)$obj->Total_Count("re_tbl_agent", "ag_status=0 AND entry_by=$id");

$customerMonthlyBill   = (float)$obj->get_sum_by_cond('taka', 're_tbl_agent', "ag_id>0 AND entry_by=$id");
$resellerMonthlyBill   = (float)$obj->get_sum_by_cond('re_taka', 're_tbl_agent', "ag_id>0 AND entry_by=$id");

$totalDueBill          = (float)$obj->get_sum_by_cond('dueadvance', 're_tbl_agent', "dueadvance>0 AND entry_by=$id");
$totalAdvanceBillRaw   = (float)$obj->get_sum_by_cond('dueadvance', 're_tbl_agent', "dueadvance<0 AND entry_by=$id");
$totalAdvanceBill      = abs($totalAdvanceBillRaw);

$availableBalance      = (float)$obj->get_sum_by_cond('balance', 're_vw_user_info', "UserType='RE' AND UserId=$id");
$paymentDueAdvanceRaw  = (float)$obj->get_sum_by_cond('dueadvance', 're_vw_user_info', "UserType='RE' AND UserId=$id");

$totalBandwidthSell    = (float)$obj->get_sum_by_cond('int_mb', 're_tbl_agent', "entry_by=$id");
$totalCollection       = (float)$obj->get_sum_by_cond('acc_amount', 're_tbl_account', "agent_id>0 AND acc_type!=1 AND entry_by=$id");


$months       = [];
$collections  = [];
$customers12  = [];

for ($i = 11; $i >= 0; $i--) {
  $time = strtotime("-$i months");
  $months[] = date('M Y', $time);

  $m = date('m', $time);
  $y = date('Y', $time);

  // Collection (per month)
  $c = $obj->get_sum_by_cond(
    'acc_amount',
    're_tbl_account',
    "MONTH(entry_date)='$m'
         AND YEAR(entry_date)='$y'
         AND agent_id>0
         AND acc_type!=1
         AND entry_by=$id"
  );
  $collections[] = $c ? (float)$c : 0;

  // Customer joined count (per month)
  $cc = $obj->Total_Count(
    're_tbl_agent',
    "MONTH(entry_date)='$m'
         AND YEAR(entry_date)='$y'
         AND entry_by=$id"
  );
  $customers12[] = (int)$cc;
}
?>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Outfit:wght@400;600;700;800&display=swap');

  :root {
    --bg: radial-gradient(circle at 8% 8%, #ecfeff 0, #f8fafc 34%, #fff7ed 70%, #f8fafc 100%);
    --text: #0f172a;
    --muted: #475569;
    --border: #dbe4f1;
    --shadow: 0 14px 30px rgba(15, 23, 42, .12);
    --shadow2: 0 10px 22px rgba(15, 23, 42, .09);
    --radius: 16px;
  }

  .dashboard-wrap {
    font-family: 'Outfit', 'Segoe UI', sans-serif;
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px;
  }

  .dashboard-title {
    margin: 0 0 16px;
    font-size: 19px;
    font-weight: 800;
    letter-spacing: .2px;
    color: var(--text);
  }

  .grid-gap {
    margin-bottom: 16px;
  }

  .kpi-card {
    background: linear-gradient(135deg, #0ea5e9, #2563eb);
    border: 1px solid rgba(255, 255, 255, .2);
    border-radius: var(--radius);
    padding: 14px;
    box-shadow: var(--shadow2);
    min-height: 118px;
    position: relative;
    overflow: hidden;
    transition: transform .18s ease, box-shadow .18s ease;
  }

  .kpi-card:hover {
    transform: translateY(-3px);
    box-shadow: var(--shadow);
  }

  .kpi-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
  }

  .kpi-icon {
    width: 46px;
    height: 46px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 19px;
    color: #fff;
    background: rgba(15, 23, 42, .32);
    box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .22);
  }

  .kpi-title {
    margin: 0;
    font-size: 12px;
    font-weight: 700;
    color: rgba(255, 255, 255, .96);
    letter-spacing: .4px;
    text-transform: uppercase;
  }

  .kpi-value {
    margin: 10px 0 0;
    font-size: 25px;
    font-weight: 800;
    color: #fff;
    line-height: 1.1;
    text-shadow: 0 3px 10px rgba(15, 23, 42, .2);
  }

  .kpi-sub {
    margin-top: 6px;
    font-size: 12px;
    color: rgba(255, 255, 255, .9);
  }

  .kpi-accent {
    position: absolute;
    right: -30px;
    top: -34px;
    width: 132px;
    height: 132px;
    border-radius: 50%;
    background: rgba(255, 255, 255, .18);
    filter: blur(1px);
  }

  .kpi-card::after {
    content: "";
    position: absolute;
    left: -26px;
    bottom: -45px;
    width: 142px;
    height: 142px;
    border-radius: 50%;
    background: rgba(255, 255, 255, .12);
  }

  .kpi-success {
    background: linear-gradient(135deg, #16a34a, #15803d);
  }

  .kpi-danger {
    background: linear-gradient(135deg, #ef4444, #dc2626);
  }

  .kpi-purple {
    background: linear-gradient(135deg, #8b5cf6, #7c3aed);
  }

  .kpi-teal {
    background: linear-gradient(135deg, #0ea5a5, #0f766e);
  }

  .kpi-orange {
    background: linear-gradient(135deg, #f59e0b, #ea580c);
  }

  .chart-card {
    background: linear-gradient(145deg, #fff, #f8fbff);
    border: 1px solid #e2e8f0;
    border-radius: var(--radius);
    box-shadow: var(--shadow2);
    padding: 14px 14px 10px;
    margin-bottom: 16px;
    position: relative;
    overflow: hidden;
  }

  .chart-card::before {
    content: "";
    position: absolute;
    top: -60px;
    right: -60px;
    width: 160px;
    height: 160px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(14, 165, 233, .16), rgba(14, 165, 233, 0));
  }

  .chart-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-bottom: 10px;
    position: relative;
    z-index: 2;
  }

  .chart-title {
    margin: 0;
    font-size: 15px;
    font-weight: 800;
    color: var(--text);
  }

  .chart-note {
    font-size: 12px;
    color: #0f766e;
    background: #ccfbf1;
    border: 1px solid #99f6e4;
    border-radius: 999px;
    padding: 4px 10px;
    font-weight: 700;
  }

  .chart-card canvas {
    width: 100% !important;
    height: 300px !important;
    position: relative;
    z-index: 2;
  }

  .rolling-card {
    border-radius: 16px;
    box-shadow: 0 14px 34px rgba(15, 23, 42, 0.11);
    border: 1px solid #dbe4f1;
    background: linear-gradient(150deg, #fff, #f8fbff);
  }

  .rolling-table td {
    width: 14.28%;
    height: 106px;
    text-align: center;
    vertical-align: middle;
    border: 1px solid #edf2f7;
    transition: 0.3s;
    padding: 10px;
    border-radius: 12px;
  }

  .rolling-table td:hover {
    background: #eef8ff;
    transform: translateY(-2px);
  }

  .day-number {
    font-weight: 800;
    font-size: 17px;
    display: block;
    color: #0f172a;
  }

  .badge-count {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 20px;
    background: #fee2e2;
    color: #b91c1c;
    display: inline-block;
    margin-top: 6px;
    max-width: 100%;
    word-wrap: break-word;
  }

  .today-box {
    background: linear-gradient(135deg, #0891b2, #2563eb);
    color: white !important;
    border-radius: 8px;
  }

  .calendar-header {
    font-weight: 800;
    font-size: 19px;
    margin-bottom: 15px;
    color: #0f172a;
  }

  .range-text {
    font-size: 13px;
    color: #475569;
    font-weight: 600;
  }

  .rolling-table {
    table-layout: fixed;
    width: 100%;
  }

  .rolling-table a {
    text-decoration: none;
    display: block;
  }

  @media (max-width: 767px) {
    .dashboard-wrap {
      padding: 12px;
    }

    .kpi-card {
      min-height: 106px;
    }

    .kpi-value {
      font-size: 22px;
    }

    .chart-card canvas {
      height: 250px !important;
    }
  }
</style>





<div class="dashboard-wrap">

  <div class="dashboard-title">Reseller Dashboard Overview</div>

  <div class="row grid-gap">

    <a href="?page=reseller-all-customer-list" class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Total Customer</p>
            <div class="kpi-value"><?php echo $totalCustomer; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-user-plus"></i></div>
        </div>
        <div class="kpi-sub">All registered customers</div>
      </div>
    </a>

    <a href="?page=reseller-all-customer-list&active=1" class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-success">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Active Customer</p>
            <div class="kpi-value"><?php echo $totalActiveCustomer; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-check-circle"></i></div>
        </div>
        <div class="kpi-sub">Currently active connections</div>
      </div>
    </a>

    <a href="?page=reseller-all-customer-list&inactive=1" class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-danger">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Inactive Customer</p>
            <div class="kpi-value"><?php echo $totalInactiveCustomer; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-times-circle"></i></div>
        </div>
        <div class="kpi-sub">Currently inactive users</div>
      </div>
    </a>

    <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-purple">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Customer Monthly Bill</p>
            <div class="kpi-value"><?php echo $customerMonthlyBill ?: 0; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-credit-card"></i></div>
        </div>
        <div class="kpi-sub">Total customer package bill</div>
      </div>
    </div>

  </div><!-- row -->

  <div class="row grid-gap">


    <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-success">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Available Balance</p>
            <div class="kpi-value"><?php echo $availableBalance ?: 0; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-wallet"></i></div>
        </div>
        <div class="kpi-sub">Wallet balance</div>
      </div>
    </div>
    <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-purple">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Payment Due/Advance</p>
            <div class="kpi-value">
              <?php $d = $paymentDueAdvanceRaw ?: 0;
              echo ($d > 0) ? $d : abs($d); ?>
            </div>
          </div>
          <div class="kpi-icon"><i class="fa fa-exchange"></i></div>
        </div>
        <div class="kpi-sub">Your due/advance summary</div>
      </div>
    </div>

    <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-orange">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Bandwidth Sell (MB)</p>
            <div class="kpi-value"><?php echo $totalBandwidthSell ?: 0; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-bolt"></i></div>
        </div>
        <div class="kpi-sub">Total sold bandwidth</div>
      </div>
    </div>

    <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12">
      <div class="kpi-card kpi-teal">
        <div class="kpi-accent"></div>
        <div class="kpi-top">
          <div>
            <p class="kpi-title">Total Collection</p>
            <div class="kpi-value"><?php echo $totalCollection ?: 0; ?></div>
          </div>
          <div class="kpi-icon"><i class="fa fa-line-chart"></i></div>
        </div>
        <div class="kpi-sub">Collected amount (non-opening)</div>
      </div>
    </div>

  </div><!-- row -->




  <!-- billing calender table start -->
  <?php
  // ====== DATE RANGE LOGIC ======
  $todayDate = date('Y-m-d');
  $startDate = date('Y-m-d', strtotime('-5 days'));
  $endDate   = date('Y-m-d', strtotime('+24 days')); // total 30 days

  // ====== FETCH BILLING COUNT ======
  $rawBillData = $obj->raw_sql(
    "SELECT DATE(mikrotik_disconnect) as bill_date, COUNT(*) as total
    FROM re_tbl_agent
    WHERE entry_by = $id 
      AND mikrotik_disconnect BETWEEN DATE_SUB(CURDATE(), INTERVAL 5 DAY)
      AND DATE_ADD(CURDATE(), INTERVAL 24 DAY)
    GROUP BY DATE(mikrotik_disconnect)
    ORDER BY bill_date ASC
"
  );

  $billingData = [];
  foreach ($rawBillData as $single) {
    $billingData[$single['bill_date']] = (int)$single['total'];
  }

  // ====== MONTH TITLE LOGIC ======
  $startMonth = date('F Y', strtotime($startDate));
  $endMonth   = date('F Y', strtotime($endDate));

  if ($startMonth == $endMonth) {
    $monthTitle = $startMonth;
  } else {
    $monthTitle = $startMonth . " - " . $endMonth;
  }
  ?>



  <div class="row justify-content-center">
    <div class="col-md-6">
      <div class="card p-4 rolling-card">

        <!-- ===== HEADER ===== -->
        <div class="text-center calendar-header">
          <?php echo '<h6 class="fw-bold">' . "Customers with Upcoming Disconnects" . "</h6>"; ?>

          <?php echo $monthTitle; ?>
          <div class="range-text">
            <?php echo date('d M Y', strtotime($startDate)); ?>
            -
            <?php echo date('d M Y', strtotime($endDate)); ?>
          </div>
        </div>

        <!-- ===== CALENDAR TABLE ===== -->
        <table class="table rolling-table">
          <tr>
            <?php
            $current = strtotime($startDate);
            $end     = strtotime($endDate);
            $count   = 0;

            while ($current <= $end) {

              if ($count % 4 == 0 && $count != 0) {
                echo "</tr><tr>";
              }

              $dateFull = date('Y-m-d', $current);
              $dayOnly  = date('d', $current);
              $isToday  = ($dateFull == $todayDate) ? "today-box" : "";

              echo "<td class='$isToday'>";
              echo "<a href='?page=reseller-bill-collection&disconnect_date=$dateFull'>";
              echo "<span class='day-number'>$dayOnly</span>";
              $customerWord = isset($billingData[$dateFull]) && $billingData[$dateFull] > 1 ? "Customers" : "Customer";
              if (isset($billingData[$dateFull])) {
                echo "<span class='badge-count'>
                " . $billingData[$dateFull] . " $customerWord
              </span>";
              }
              echo "</a>";
              echo "</td>";

              $current = strtotime("+1 day", $current);
              $count++;
            }
            ?>
          </tr>
        </table>

      </div>
    </div>

    <!-- charts -->
    <div class="col-md-6">
      <div class="row">
        <div class="col-md-12">
          <div class="chart-card">
            <div class="chart-head">
              <h6 class="chart-title">Collection (Last 12 Months)</h6>
              <span class="chart-note">Entry by: <?php echo (int)$id; ?></span>
            </div>
            <canvas id="accountsChart"></canvas>
          </div>
        </div>

        <div class="col-md-12">
          <div class="chart-card">
            <div class="chart-head">
              <h6 class="chart-title">New Customers (Last 12 Months)</h6>
              <span class="chart-note">Auto updated</span>
            </div>
            <canvas id="cusChart"></canvas>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- billing calender table end -->
</div>

<!-- If jQuery already loaded globally, you can remove this -->
<script src="asset/js/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.min.js" crossorigin="anonymous"></script>

<script>
  /* =========================
   5) PHP -> JS DATA
   ========================= */
  const chartLabels = <?php echo json_encode($months); ?>;
  const collectionData = <?php echo json_encode($collections); ?>;
  const customerData = <?php echo json_encode($customers12); ?>;

  /* =========================
     6) CHARTS
     ========================= */
  const accountsCanvas = document.getElementById('accountsChart');
  const accountsCtx = accountsCanvas.getContext('2d');
  const collectionFill = accountsCtx.createLinearGradient(0, 0, 0, 320);
  collectionFill.addColorStop(0, 'rgba(37, 99, 235, 0.40)');
  collectionFill.addColorStop(1, 'rgba(37, 99, 235, 0.02)');

  const collectionStroke = accountsCtx.createLinearGradient(0, 0, 420, 0);
  collectionStroke.addColorStop(0, '#0284c7');
  collectionStroke.addColorStop(1, '#2563eb');

  new Chart(accountsCanvas, {
    type: 'line',
    data: {
      labels: chartLabels,
      datasets: [{
        label: 'Total Collection',
        data: collectionData,
        borderColor: collectionStroke,
        backgroundColor: collectionFill,
        borderWidth: 3,
        pointRadius: 4,
        pointHoverRadius: 6,
        pointBackgroundColor: '#fff',
        pointBorderWidth: 2,
        pointBorderColor: '#2563eb',
        tension: 0.38,
        fill: true
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          labels: {
            color: '#0f172a',
            boxWidth: 12,
            usePointStyle: true,
            pointStyle: 'circle',
            font: {
              weight: '700'
            }
          }
        },
        tooltip: {
          backgroundColor: 'rgba(15, 23, 42, 0.94)',
          titleColor: '#fff',
          bodyColor: '#e2e8f0',
          padding: 10,
          displayColors: false
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          },
          ticks: {
            color: '#64748b'
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(148, 163, 184, 0.25)',
            drawBorder: false
          },
          ticks: {
            color: '#64748b'
          }
        }
      }
    }
  });

  const customerCanvas = document.getElementById('cusChart');
  const customerCtx = customerCanvas.getContext('2d');
  const customerBar = customerCtx.createLinearGradient(0, 0, 0, 320);
  customerBar.addColorStop(0, 'rgba(249, 115, 22, 0.95)');
  customerBar.addColorStop(1, 'rgba(245, 158, 11, 0.78)');

  new Chart(customerCanvas, {
    type: 'bar',
    data: {
      labels: chartLabels,
      datasets: [{
        label: 'Total Customers',
        data: customerData,
        backgroundColor: customerBar,
        borderColor: '#ea580c',
        borderWidth: 1,
        borderRadius: 10,
        borderSkipped: false,
        maxBarThickness: 26
      }]
    },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          labels: {
            color: '#0f172a',
            boxWidth: 12,
            usePointStyle: true,
            pointStyle: 'rectRounded',
            font: {
              weight: '700'
            }
          }
        },
        tooltip: {
          backgroundColor: 'rgba(15, 23, 42, 0.94)',
          titleColor: '#fff',
          bodyColor: '#e2e8f0',
          padding: 10,
          displayColors: false
        }
      },
      scales: {
        x: {
          grid: {
            display: false
          },
          ticks: {
            color: '#64748b'
          }
        },
        y: {
          beginAtZero: true,
          grid: {
            color: 'rgba(148, 163, 184, 0.25)',
            drawBorder: false
          },
          ticks: {
            color: '#64748b'
          }
        }
      }
    }
  });
</script>
