<?php

require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

// Require authentication
requireAuth();

// Get current business
$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

// Log activity
logActivity('reports_view', 'Viewed reports page');

$from = $_GET['from'] ?? date('Y-m-01');
$to   = $_GET['to']   ?? date('Y-m-d');
$business_id = $current_business['business_id'];

// fetch paid orders in range for this business
$rows = all_rows("
    SELECT o.*, c.name AS customer_name, c.mobile_no AS customer_mobile
    FROM orders o
    LEFT JOIN customer c ON o.customer_sno = c.sno
    WHERE o.business_id = ? AND DATE(o.created_at) BETWEEN ? AND ?
      AND o.status IN ('PAID', 'DUE')
    ORDER BY o.created_at DESC
", [$business_id, $from, $to]);

$order_count = count($rows);
$subtotal = 0.0;
$discount = 0.0;
$tax = 0.0;
$total = 0.0;

// ✅ store processed rows separately
$calc_rows = [];
$by_payment = [];

foreach ($rows as $r) {
    $row_subtotal = (float)$r['subtotal'];
    $row_discount = (float)$r['discount'];

    // Only include GST if enabled
    $row_tax = (!empty($r['gst_enabled']) && (int)$r['gst_enabled'] === 1) ? (float)$r['tax'] : 0.0;

    $row_total = round(($row_subtotal - $row_discount) + $row_tax, 2);

    // accumulate for report summary
    $subtotal += $row_subtotal;
    $discount += $row_discount;
    $tax      += $row_tax;
    $total    += $row_total;

    $pm = $r['payment_method'] ?: 'UNKNOWN';
    if (!isset($by_payment[$pm])) $by_payment[$pm] = 0.0;
    $by_payment[$pm] += $row_total;

    // push updated row
    $r['tax']   = $row_tax;
    $r['total'] = $row_total;
    $calc_rows[] = $r;
}
?>
<style>
  body {
    background-image: url("<?php echo BASE_URL; ?>/public/background.jpg");
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
  }
  .container{
    background: rgba(255, 255, 255, 0.88);
    border-radius: 16px;
    padding: 1rem;
    box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
    backdrop-filter: blur(2px);
  }
</style>
<h3 class="mb-3">Reports</h3>

<form class="row g-2 align-items-end mb-3" method="get" action="">
  <input type="hidden" name="r" value="reports">

  <div class="col-auto">
    <label class="form-label">Start</label>
    <input class="form-control" type="date" name="from" value="<?= e($from) ?>">
  </div>

  <div class="col-auto">
    <label class="form-label">End</label>
    <input class="form-control" type="date" name="to" value="<?= e($to) ?>">
  </div>

  <div class="col-auto">
    <button class="btn btn-outline-primary">Filter</button>
  </div>

  <div class="col-auto">
    <a class="btn btn-success" 
       href="<?= BASE_URL ?>/public/?r=reports.csv&from=<?= e($from) ?>&to=<?= e($to) ?>">
       Export CSV
    </a>
  </div>
</form>

<div class="row g-2 mb-3">
  <div class="col">
    <div class="form-control">Orders: <strong><?= $order_count ?></strong></div>
  </div>
  <div class="col">
    <div class="form-control">Subtotal: <strong>₹<?= number_format($subtotal,2) ?></strong></div>
  </div>
  <div class="col">
    <div class="form-control">Discount: <strong>₹<?= number_format($discount,2) ?></strong></div>
  </div>
  <div class="col">
    <div class="form-control">Tax: <strong>₹<?= number_format($tax,2) ?></strong></div>
  </div>
  <div class="col">
    <div class="form-control">Total: <strong>₹<?= number_format($total,2) ?></strong></div>
  </div>
</div>

<div class="mb-3">
  <?php foreach($by_payment as $pm=>$amt): ?>
    <span class="badge bg-secondary me-2">
      <?= strtoupper(e($pm)) ?>: ₹ <?= number_format($amt,2) ?>
    </span>
  <?php endforeach; ?>
</div>

<div class="card p-3 shadow-sm">
  <table class="table table-hover align-middle mb-0">
    <thead class="table-light">
      <tr>
        <th>#</th>
        <th>Date</th>
        <th>Table</th>
        <th>Payment</th>
        <th>Customer Name</th>
        <th>Customer Number</th>
        <th>Subtotal</th>
        <th>Discount</th>
        <th>Tax</th>
        <th>Total</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($calc_rows as $row): ?>
        <tr>
          <td>
            <a href="<?= BASE_URL ?>/?r=orders/show&id=<?= e($row['id']) ?>">
              #<?= e($row['id']) ?>
            </a>
          </td>
          <td><?= e(date("Y-m-d H:i", strtotime($row['created_at']))) ?></td>
          <td><?= e($row['table_no'] ?: '-') ?></td>
          <td>
              <?php if ($row['status'] === 'PAID'): ?>
                  <span class="badge bg-success">PAID</span>
              <?php elseif ($row['status'] === 'DUE'): ?>
                  <span class="badge bg-danger">DUE</span>
              <?php else: ?>
                  <span class="badge bg-secondary"><?= e($row['status']) ?></span>
              <?php endif; ?>
            </td>

          <td><?= e($row['customer_name'] ?: '-') ?></td>
          <td><?= e($row['customer_mobile'] ?: '-') ?></td>

          <td>₹<?= number_format($row['subtotal'],2) ?></td>
          <td>₹<?= number_format($row['discount'],2) ?></td>
          <td>₹<?= number_format($row['tax'],2) ?></td>
          <td>₹<?= number_format($row['total'],2) ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
</div>
