<?php
session_start();
require 'config.php';
if (empty($_SESSION['user'])) header('Location: login.php');
include 'navbar.php';

// ----- جلب المواد للفلاتر -----
$products = $pdo->query("SELECT id, name FROM products ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// ----- الفلاتر -----
$product_filter = $_GET['product_id'] ?? '';
$from_date = $_GET['from'] ?? '';
$to_date = $_GET['to'] ?? '';

// ----- استعلام المبيعات -----
$query_sales = "SELECT s.*, p.name 
                FROM sales s 
                JOIN products p ON p.id = s.product_id 
                WHERE 1";
if ($product_filter) $query_sales .= " AND s.product_id = :pid";
if ($from_date) $query_sales .= " AND s.sale_date >= :from";
if ($to_date) $query_sales .= " AND s.sale_date <= :to";
$query_sales .= " ORDER BY s.sale_date DESC";

$stmt_sales = $pdo->prepare($query_sales);
if ($product_filter) $stmt_sales->bindParam(':pid', $product_filter);
if ($from_date) $stmt_sales->bindParam(':from', $from_date);
if ($to_date) $stmt_sales->bindParam(':to', $to_date);
$stmt_sales->execute();
$sales = $stmt_sales->fetchAll(PDO::FETCH_ASSOC);

// ----- استعلام حركات المخزون -----
$query_movements = "SELECT m.*, p.name 
                    FROM stock_movements m 
                    JOIN products p ON p.id = m.product_id 
                    WHERE 1";
if ($product_filter) $query_movements .= " AND m.product_id = :pid";
if ($from_date) $query_movements .= " AND m.date_added >= :from";
if ($to_date) $query_movements .= " AND m.date_added <= :to";
$query_movements .= " ORDER BY m.date_added DESC";

$stmt_movements = $pdo->prepare($query_movements);
if ($product_filter) $stmt_movements->bindParam(':pid', $product_filter);
if ($from_date) $stmt_movements->bindParam(':from', $from_date);
if ($to_date) $stmt_movements->bindParam(':to', $to_date);
$stmt_movements->execute();
$movements = $stmt_movements->fetchAll(PDO::FETCH_ASSOC);
?>

<!doctype html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>📊 التقارير</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container py-4">
  <h3 class="mb-4 text-center">📊 التقارير</h3>

  <!-- الفلاتر -->
  <form method="get" class="card p-3 mb-4 shadow-sm">
    <div class="row g-2 align-items-end">
      <div class="col-md-4">
        <label class="form-label">المادة</label>
        <select name="product_id" class="form-select">
          <option value="">الكل</option>
          <?php foreach($products as $p): ?>
            <option value="<?=$p['id']?>" <?=($p['id']==$product_filter?'selected':'')?>><?=$p['name']?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-3">
        <label class="form-label">من تاريخ</label>
        <input type="date" name="from" value="<?=$from_date?>" class="form-control">
      </div>
      <div class="col-md-3">
        <label class="form-label">إلى تاريخ</label>
        <input type="date" name="to" value="<?=$to_date?>" class="form-control">
      </div>
      <div class="col-md-2 text-end">
        <button type="submit" class="btn btn-primary w-100">🔍 بحث</button>
      </div>
    </div>
  </form>

  <!-- التبويبات -->
  <ul class="nav nav-tabs mb-3" id="reportTabs">
    <li class="nav-item">
      <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#sales">💰 المبيعات</button>
    </li>
    <li class="nav-item">
      <button class="nav-link" data-bs-toggle="tab" data-bs-target="#stock">📦 حركات المخزون</button>
    </li>
  </ul>

  <div class="tab-content">
    <!-- المبيعات -->
    <div class="tab-pane fade show active" id="sales">
      <div class="d-flex justify-content-end mb-2">
        <a href="export_sales_pdf.php" class="btn btn-danger me-2">تحميل PDF</a>
        <a href="export_sales_excel.php" class="btn btn-success">تحميل Excel</a>
      </div>
      <div class="table-responsive">
        <table class="table table-bordered table-striped bg-white align-middle">
          <thead class="table-warning text-center">
            <tr>
              <th>المادة</th>
              <th>عدد الشوالات</th>
              <th>الوزن الكلي (كغ)</th>
              <th>السعر</th>
              <th>الملاحظة</th>
              <th>التاريخ</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($sales): foreach($sales as $s): ?>
              <tr>
                <td><?=$s['name']?></td>
                <td><?=$s['bags_sold']?></td>
                <td><?=$s['weight_sold']?></td>
                <td><?=$s['price']?></td>
                <td><?=$s['note']?></td>
                <td><?=$s['sale_date']?></td>
              </tr>
            <?php endforeach; else: ?>
              <tr><td colspan="6" class="text-center text-muted">لا توجد مبيعات حسب الفلتر</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- حركات المخزون -->
    <div class="tab-pane fade" id="stock">
      <div class="d-flex justify-content-end mb-2">
        <a href="export_stock_pdf.php" class="btn btn-danger me-2">تحميل PDF</a>
        <a href="export_stock_excel.php" class="btn btn-success">تحميل Excel</a>
      </div>
      <div class="table-responsive">
        <table class="table table-bordered table-striped bg-white align-middle">
          <thead class="table-primary text-center">
            <tr>
              <th>المادة</th>
              <th>عدد الشوالات</th>
              <th>وزن الشوال (كغ)</th>
              <th>الوزن الكلي (كغ)</th>
              <th>نوع الحركة</th>
              <th>الملاحظة</th>
              <th>التاريخ</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($movements): foreach($movements as $m): ?>
              <tr>
                <td><?=$m['name']?></td>
                <td><?=$m['bags_count']?></td>
                <td><?=$m['weight_per_bag']?></td>
                <td><?=$m['total_weight']?></td>
                <td><?=($m['movement_type'] === 'addition' ? 'إضافة' : 'خصم/بيع')?></td>
                <td><?=$m['note'] ?? ''?></td>
                <td><?=$m['date_added']?></td>
              </tr>
            <?php endforeach; else: ?>
              <tr><td colspan="7" class="text-center text-muted">لا توجد حركات حسب الفلتر</td></tr>
            <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <a href="index.php" class="btn btn-secondary mt-4">⬅ رجوع</a>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
