<?php
require_once __DIR__ . '/helpers.php';
$page_title = t('purchases_report', 'جرد المشتريات');
$finance_active = 'purchases_report';
$finance_group = 'purchases';
$UA_FORCE_DESIGN_V2 = true;
$uaAndroidPurchasesReport = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
if ($uaAndroidPurchasesReport) $UA_PAGE_CSS = ['assets/css/android_purchases_report.css'];
include __DIR__ . '/header.php';
include __DIR__ . '/sidebar.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/purchases_lib.php';
require_once __DIR__ . '/settings_store.php';

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

ensure_purchase_tables($conn);

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

$stmt = $conn->prepare("SELECT p.*, (SELECT COUNT(*) FROM shop_purchase_items it WHERE it.purchase_id=p.id) AS items_count
                        FROM shop_purchases p
                        WHERE DATE(p.created_at) BETWEEN ? AND ?
                        ORDER BY p.id DESC");
$stmt->bind_param('ss', $from, $to);
$stmt->execute();
$rows = $stmt->get_result();

$sum_syp = 0.0;
$sum_usd = 0.0;
while ($r = $rows->fetch_assoc()) {
    if (($r['currency'] ?? 'SYP') === 'USD') $sum_usd += (float)($r['total'] ?? 0);
    else $sum_syp += (float)($r['total'] ?? 0);
}
$rows->data_seek(0);

if ($uaAndroidPurchasesReport) {
  require __DIR__ . '/android_purchases_report.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">
        <h1 class="mb-0"><?= h($page_title) ?></h1>
        <a class="btn btn-primary" href="purchases_new.php"><i class="fa fa-plus"></i> <?= t('new_purchase','إضافة مشتريات') ?></a>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php include __DIR__ . '/finance_tabs.php'; ?>

      <div class="card ui-card mb-3">
        <div class="card-body">
          <form class="ua-purchase-filter" method="get">
            <label class="mr-2"><?= t('from','من') ?></label>
            <input type="date" name="from" class="form-control mr-3" value="<?= h($from) ?>">
            <label class="mr-2"><?= t('to','إلى') ?></label>
            <input type="date" name="to" class="form-control mr-3" value="<?= h($to) ?>">
            <button class="btn btn-secondary" type="submit"><?= t('filter','تصفية') ?></button>
          </form>
        </div>
      </div>

      <div class="row">
        <div class="col-md-6">
          <div class="small-box bg-info pu-summary-box">
            <div class="inner">
              <h3><?= number_format($sum_syp,2) ?> <small>SYP</small></h3>
              <p><?= t('total_purchases_syp','إجمالي المشتريات بالليرة') ?></p>
            </div>
            <div class="icon"><i class="fa fa-shopping-bag"></i></div>
          </div>
        </div>
        <div class="col-md-6">
          <div class="small-box bg-success pu-summary-box">
            <div class="inner">
              <h3><?= number_format($sum_usd,2) ?> <small>USD</small></h3>
              <p><?= t('total_purchases_usd','إجمالي المشتريات بالدولار') ?></p>
            </div>
            <div class="icon"><i class="fa fa-dollar"></i></div>
          </div>
        </div>
      </div>

      <div class="card ui-card">
        <div class="card-body p-0">
          <div class="table-responsive">
            <table class="table table-hover mb-0">
              <thead>
                <tr>
                  <th>#</th>
                  <th><?= t('supplier','المورد') ?></th>
                  <th><?= t('invoice_no','رقم الفاتورة') ?></th>
                  <th><?= t('items','العناصر') ?></th>
                  <th><?= t('total','الإجمالي') ?></th>
                  <th><?= t('currency','العملة') ?></th>
                  <th><?= t('date','التاريخ') ?></th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
              <?php if ($rows->num_rows === 0): ?>
                <tr><td colspan="8" class="text-center text-muted p-4"><?= t('no_purchases','لا يوجد مشتريات') ?></td></tr>
              <?php else: while($row=$rows->fetch_assoc()): ?>
                <tr>
                  <td><?= (int)$row['id'] ?></td>
                  <td><?= h($row['supplier_name'] ?? '-') ?></td>
                  <td><?= h($row['invoice_no'] ?? '-') ?></td>
                  <td><?= (int)($row['items_count'] ?? 0) ?></td>
                  <td><?= number_format((float)($row['total'] ?? 0),2) ?></td>
                  <td><?= h($row['currency'] ?? 'SYP') ?></td>
                  <td><?= h($row['created_at'] ?? '') ?></td>
                  <td class="text-right">
                    <a class="btn btn-sm btn-outline-primary" href="purchases_view.php?id=<?= (int)$row['id'] ?>"><i class="fa fa-eye"></i></a>
                  </td>
                </tr>
              <?php endwhile; endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
<?php include __DIR__ . '/footer.php'; ?>
