<?php
header('Content-Type: application/json');
session_start();

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

require_once '../config/db.php';

try {
    $db = new Database();
    $pdo = $db->getConnection();
    
    // عدد المنتجات
    $stmt = $pdo->query("SELECT COUNT(*) FROM products");
    $products_count = $stmt->fetchColumn();
    
    // مبيعات اليوم
    $stmt = $pdo->query("SELECT SUM(price * quantity) FROM sales WHERE date(sale_date) = date('now')");
    $today_sales = $stmt->fetchColumn() ?: 0;
    
    // عدد الزبائن
    $stmt = $pdo->query("SELECT COUNT(*) FROM customers");
    $customers_count = $stmt->fetchColumn();
    
    // إجمالي الديون
    $stmt = $pdo->query("SELECT SUM(amount - paid) FROM debts");
    $total_debts = $stmt->fetchColumn() ?: 0;
    
    echo json_encode([
        'products_count' => $products_count,
        'today_sales' => number_format($today_sales, 2),
        'customers_count' => $customers_count,
        'total_debts' => number_format($total_debts, 2)
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
