<?php
require_once __DIR__ . '/helpers.php';
$page_title = t('sales_report', 'جرد المبيعات');
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidSalesSummary = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidSalesSummary) $UA_PAGE_CSS = ['assets/css/android_sales_summary.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/shop_lib.php';

require_login();
if(function_exists('require_perm')) require_perm('can_manage_sales');

// تأكد من الجداول
if(function_exists('ensure_shop_tables')) ensure_shop_tables($conn);

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

// مجموع المبيعات
$stmt = $conn->prepare("SELECT COUNT(*) as cnt, COALESCE(SUM(total),0) as total_sum FROM shop_sales WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
$sumRow = $stmt->get_result()->fetch_assoc() ?: ['cnt'=>0,'total_sum'=>0];
$stmt->close();

// أفضل المواد
$best = [];
	// ملاحظة: بعض قواعد البيانات القديمة لا تحتوي على product_id داخل shop_sale_items.
	// لذلك نعتمد على اسم المادة المخزن داخل sale_items.name بدون أي JOIN.
	$sql = "SELECT
	          si.name AS name,
	          COALESCE(SUM(si.qty),0) qty_sum,
	          COALESCE(SUM(si.line_total),0) total_sum
	        FROM shop_sale_items si
	        JOIN shop_sales s ON s.id = si.sale_id
	        WHERE DATE(s.created_at) BETWEEN ? AND ?
	        GROUP BY si.name
	        ORDER BY total_sum DESC
	        LIMIT 10";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
$res = $stmt->get_result();
while($r = $res->fetch_assoc()) $best[] = $r;
$stmt->close();

// أحدث فواتير
$recent = [];
$sql = "SELECT id, customer_name, total, created_at FROM shop_sales ORDER BY id DESC LIMIT 20";
$res = $conn->query($sql);
if($res) while($r = $res->fetch_assoc()) $recent[] = $r;

$active_tab = 'summary';
if ($uaAndroidSalesSummary) {
  require __DIR__ . '/android_sales_summary.php';
  include __DIR__ . '/footer.php';
  return;
}
?>

<div class="content-wrapper ua-extracted-page">
  <section class="content-header">
    <div class="container-fluid">
      <div class="d-flex align-items-center justify-content-between flex-wrap">
        <h1 class="mb-0"><?= h($page_title) ?></h1>
        <form class="form-inline" method="get">
          <label class="mr-2"><?= t('from', 'من') ?></label>
          <input class="form-control form-control-sm mr-2" type="date" name="from" value="<?= h($from) ?>">
          <label class="mr-2"><?= t('to', 'إلى') ?></label>
          <input class="form-control form-control-sm mr-2" type="date" name="to" value="<?= h($to) ?>">
          <button class="btn btn-sm btn-primary" type="submit"><?= t('filter', 'عرض') ?></button>
        </form>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <div class="row">
        <div class="col-md-4">
          <div class="card card-outline card-primary">
            <div class="card-body">
              <div class="text-muted"><?= t('sales_count', 'عدد فواتير المبيعات') ?></div>
              <div class="ua-u-fs-28 ua-u-fw-800"><?= (int)$sumRow['cnt'] ?></div>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="card card-outline card-success">
            <div class="card-body">
              <div class="text-muted"><?= t('sales_total', 'إجمالي المبيعات') ?></div>
              <div class="ua-u-fs-28 ua-u-fw-800"><?= number_format((float)$sumRow['total_sum'], 0) ?></div>
              <small class="text-muted"><?= t('default_currency_hint', 'حسب عملة الفاتورة') ?></small>
            </div>
          </div>
        </div>
        <div class="col-md-4">
          <div class="card card-outline card-info">
            <div class="card-body">
              <a class="btn btn-info w-100" href="sales_new.php"><i class="fa fa-plus"></i> <?= t('new_sale', 'فاتورة مبيعات جديدة') ?></a>
              <a class="btn btn-outline-primary w-100 mt-2" href="sales_history.php"><i class="fa fa-list"></i> <?= t('sales_history', 'فواتير المبيعات السابقة') ?></a>
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <div class="card">
            <div class="card-header"><b><?= t('top_items', 'أكثر المواد مبيعاً') ?></b></div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-striped mb-0">
                  <thead>
                    <tr>
                      <th><?= t('item', 'المادة') ?></th>
                      <th class="text-center"><?= t('qty', 'الكمية') ?></th>
                      <th class="text-right"><?= t('total', 'الإجمالي') ?></th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (empty($best)): ?>
                      <tr><td colspan="3" class="text-center text-muted p-3"><?= t('no_data', 'لا توجد بيانات') ?></td></tr>
                    <?php else: foreach($best as $r): ?>
                      <tr>
                        <td><?= h($r['name']) ?></td>
                        <td class="text-center"><?= number_format((float)$r['qty_sum'], 0) ?></td>
                        <td class="text-right"><?= number_format((float)$r['total_sum'], 0) ?></td>
                      </tr>
                    <?php endforeach; endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <div class="col-md-6">
          <div class="card">
            <div class="card-header"><b><?= t('recent_sales', 'آخر فواتير المبيعات') ?></b></div>
            <div class="card-body p-0">
              <div class="table-responsive">
                <table class="table table-striped mb-0">
                  <thead>
                    <tr>
                      <th>#</th>
                      <th><?= t('customer', 'العميل') ?></th>
                      <th class="text-right"><?= t('total', 'الإجمالي') ?></th>
                      <th class="text-center"><?= t('date', 'التاريخ') ?></th>
                    </tr>
                  </thead>
                  <tbody>
                    <?php if (empty($recent)): ?>
                      <tr><td colspan="4" class="text-center text-muted p-3"><?= t('no_sales', 'لا توجد فواتير مبيعات بعد') ?></td></tr>
                    <?php else: foreach($recent as $r): ?>
                      <tr>
                        <td><?= (int)$r['id'] ?></td>
                        <td><a href="sales_view.php?id=<?= (int)$r['id'] ?>"><?= h($r['customer_name'] ?? '') ?></a></td>
                        <td class="text-right"><?= number_format((float)$r['total'], 0) ?> <small class="text-muted"><?= h('' ?? '') ?></small></td>
                        <td class="text-center"><small><?= h($r['created_at']) ?></small></td>
                      </tr>
                    <?php endforeach; endif; ?>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

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

<?php include __DIR__ . '/footer.php'; ?>
