<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

// 🧱 تهيئة الجلسة المؤقتة
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';

// 🧮 الإحصائيات العامة
$total_customers  = $pdo->query("SELECT COUNT(*) FROM customers")->fetchColumn();
$total_suppliers  = $pdo->query("SELECT COUNT(*) FROM suppliers")->fetchColumn();
$total_products   = $pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();

// 🔹 إجمالي المبيعات من sales_invoices
$total_sales = $pdo->query("SELECT IFNULL(SUM(total),0) FROM sales_invoices")->fetchColumn();

// 🔹 إجمالي المشتريات من purchase_invoices
$total_purchases = $pdo->query("SELECT IFNULL(SUM(total),0) FROM purchase_invoices")->fetchColumn();

// 🔹 إجمالي الكميات في المخزون
$total_stock_qty = $pdo->query("SELECT IFNULL(SUM(quantity),0) FROM products")->fetchColumn();

// 🔹 إجمالي قيمة المخزون (الكمية × سعر التكلفة)
$total_stock_value = $pdo->query("SELECT IFNULL(SUM(quantity * cost_price),0) FROM products")->fetchColumn();

// 🔹 تجهيز الرسم البياني (آخر 7 أيام)
$sales_chart = [];
$purchases_chart = [];
$dates = [];

for ($i = 6; $i >= 0; $i--) {
  $day = date('Y-m-d', strtotime("-$i days"));
  $dates[] = $day;
  $sales_chart[] = (float)$pdo->query("SELECT IFNULL(SUM(total),0) FROM sales_invoices WHERE DATE(date)='$day'")->fetchColumn();
  $purchases_chart[] = (float)$pdo->query("SELECT IFNULL(SUM(total),0) FROM purchase_invoices WHERE DATE(date)='$day'")->fetchColumn();
}
?>

<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">

<div class="text-center mb-4">
  <h2 class="fw-bold text-primary">📊 لوحة التحكم - Wood System</h2>
  <p class="text-muted">مرحبًا بك في نظام الإدارة المحاسبية والمخزون</p>
</div>

<!-- 🟦 الصف الأول -->
<div class="row g-4 text-center mb-4">
  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#004085,#007bff);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-people"></i></div>
      <h5 class="mt-2 fw-bold">العملاء</h5>
      <h3 class="fw-bold"><?= $total_customers ?></h3>
      <a href="/wood-system/pages/customers.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#5a189a,#240046);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-truck"></i></div>
      <h5 class="mt-2 fw-bold">الموردين</h5>
      <h3 class="fw-bold"><?= $total_suppliers ?></h3>
      <a href="/wood-system/pages/suppliers.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#198754,#0a3622);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-cart-check"></i></div>
      <h5 class="mt-2 fw-bold">إجمالي المبيعات</h5>
      <h3 class="fw-bold">$<?= number_format($total_sales, 2) ?></h3>
      <a href="/wood-system/pages/sales.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#dc3545,#5a0d16);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-bag-dash"></i></div>
      <h5 class="mt-2 fw-bold">إجمالي المشتريات</h5>
      <h3 class="fw-bold">$<?= number_format($total_purchases, 2) ?></h3>
      <a href="/wood-system/pages/purchases.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>
</div>

<!-- 🟧 الصف الثاني -->
<div class="row g-4 text-center mb-4">
  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#fd7e14,#6e260a);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-box-seam"></i></div>
      <h5 class="mt-2 fw-bold">عدد المنتجات</h5>
      <h3 class="fw-bold"><?= $total_products ?></h3>
      <a href="/wood-system/pages/products.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#ffc107,#b8860b);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-stack"></i></div>
      <h5 class="mt-2 fw-bold">إجمالي الكميات بالمخزون</h5>
      <h3 class="fw-bold"><?= number_format($total_stock_qty, 2) ?></h3>
      <a href="/wood-system/pages/stock.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 text-white" style="background:linear-gradient(135deg,#17a2b8,#065f6b);border-radius:1rem;">
      <div class="fs-2"><i class="bi bi-currency-dollar"></i></div>
      <h5 class="mt-2 fw-bold">قيمة المخزون</h5>
      <h3 class="fw-bold">$<?= number_format($total_stock_value, 2) ?></h3>
      <a href="/wood-system/pages/stock.php" class="btn btn-light btn-sm mt-2 px-3">عرض</a>
    </div>
  </div>

  <div class="col-md-3 col-sm-6">
    <div class="card shadow-lg border-0 p-4 bg-white text-dark" style="border-radius:1rem;">
      <div class="fs-2 text-primary"><i class="bi bi-lightning"></i></div>
      <h5 class="mt-2 fw-bold text-muted">الوصول السريع</h5>
      <div class="d-flex flex-wrap gap-2 justify-content-center mt-2">
        <a href="/wood-system/pages/money.php" class="btn btn-outline-primary btn-sm">مقبوضات</a>
        <a href="/wood-system/pages/supplier_money.php" class="btn btn-outline-danger btn-sm">مدفوعات</a>
        <a href="/wood-system/pages/cashbox.php" class="btn btn-outline-success btn-sm">الصندوق</a>
        <a href="/wood-system/pages/transfers.php" class="btn btn-outline-dark btn-sm">تحويلات</a>
      </div>
    </div>
  </div>
</div>

<!-- الرسم البياني -->
<div class="card shadow-lg border-0 p-4 bg-white mb-5" style="border-radius:1rem;">
  <h5 class="text-center text-muted mb-3">📈 المبيعات والمشتريات خلال آخر 7 أيام</h5>
  <canvas id="salesChart" height="100"></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('salesChart');
new Chart(ctx, {
  type: 'line',
  data: {
    labels: <?= json_encode($dates) ?>,
    datasets: [
      {
        label: 'المبيعات ($)',
        data: <?= json_encode($sales_chart) ?>,
        borderColor: '#0d6efd',
        backgroundColor: 'rgba(13,110,253,0.15)',
        borderWidth: 3,
        fill: true,
        tension: .4
      },
      {
        label: 'المشتريات ($)',
        data: <?= json_encode($purchases_chart) ?>,
        borderColor: '#dc3545',
        backgroundColor: 'rgba(220,53,69,0.15)',
        borderWidth: 3,
        fill: true,
        tension: .4
      }
    ]
  },
  options: {
    scales: { y: { beginAtZero: true } },
    plugins: { legend: { labels: { font: { size: 14 } } } }
  }
});
</script>

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