<?php
session_save_path(__DIR__ . '/../tmp');
if (!is_dir(__DIR__ . '/../tmp')) mkdir(__DIR__ . '/../tmp', 0777, true);
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: /wood-system/login.php");
    exit;
}

require __DIR__ . '/../includes/db.php';
require __DIR__ . '/../includes/header.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// -------------------- الإعدادات الافتراضية --------------------
$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date   = $_GET['to'] ?? date('Y-m-d');
$cashbox_id = $_GET['cashbox_id'] ?? 'all';

// -------------------- جلب الصناديق --------------------
$cashboxes = $pdo->query("SELECT * FROM cashbox ORDER BY id ASC")->fetchAll();

// -------------------- بناء الاستعلام --------------------
$where = "WHERE date BETWEEN ? AND ?";
$params = [$from_date, $to_date];

if ($cashbox_id !== 'all') {
    $where .= " AND cashbox_id = ?";
    $params[] = $cashbox_id;
}

// -------------------- تنفيذ التقرير --------------------
$stmt = $pdo->prepare("
    SELECT category, SUM(amount) AS total
    FROM expenses
    $where
    GROUP BY category
");
$stmt->execute($params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// -------------------- إجمالي الكل --------------------
$stmt2 = $pdo->prepare("SELECT SUM(amount) AS grand_total FROM expenses $where");
$stmt2->execute($params);
$grand_total = $stmt2->fetchColumn();
?>

<h3 class="mb-4 text-primary">📊 تقرير المصاريف</h3>

<form method="get" class="card p-3 shadow-sm mb-4">
  <div class="row g-3 align-items-end">
    <div class="col-md-3">
      <label class="form-label">من تاريخ</label>
      <input type="date" class="form-control" name="from" value="<?= htmlspecialchars($from_date) ?>">
    </div>
    <div class="col-md-3">
      <label class="form-label">إلى تاريخ</label>
      <input type="date" class="form-control" name="to" value="<?= htmlspecialchars($to_date) ?>">
    </div>
    <div class="col-md-3">
      <label class="form-label">الصندوق</label>
      <select class="form-select" name="cashbox_id">
        <option value="all">جميع الصناديق</option>
        <?php foreach($cashboxes as $cb): ?>
          <option value="<?= $cb['id'] ?>" <?= $cashbox_id==$cb['id']?'selected':'' ?>>
            <?= htmlspecialchars($cb['name']) ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-3 text-end">
      <button class="btn btn-primary">🔍 عرض التقرير</button>
    </div>
  </div>
</form>

<div class="card shadow-sm">
  <div class="card-body">
    <h5 class="mb-3 text-secondary">
      من <?= htmlspecialchars($from_date) ?> إلى <?= htmlspecialchars($to_date) ?>
      <?= $cashbox_id !== 'all' ? ' | صندوق محدد' : '' ?>
    </h5>

    <?php if ($results): ?>
    <div class="table-responsive">
      <table class="table table-bordered text-center align-middle">
        <thead class="table-dark">
          <tr>
            <th>الفئة</th>
            <th>إجمالي المبلغ ($)</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($results as $r): ?>
          <tr>
            <td><?= htmlspecialchars($r['category']) ?></td>
            <td class="fw-bold text-danger"><?= number_format($r['total'], 2, '.', ',') ?> $</td>
          </tr>
        <?php endforeach; ?>
        </tbody>
        <tfoot>
          <tr class="table-secondary">
            <th>الإجمالي الكلي</th>
            <th class="fw-bold text-primary"><?= number_format($grand_total, 2, '.', ',') ?> $</th>
          </tr>
        </tfoot>
      </table>
    </div>
    <?php else: ?>
      <div class="alert alert-info text-center">لا توجد مصاريف في الفترة المحددة.</div>
    <?php endif; ?>
  </div>
</div>

<?php require __DIR__ . '/../includes/footer.php'; ?>
