<?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();
    
    // الحصول على آخر 10 مبيعات
    $stmt = $pdo->query("
        SELECT 
            s.id,
            p.name as product_name,
            s.quantity,
            s.price,
            datetime(s.sale_date) as sale_date
        FROM sales s
        JOIN products p ON p.id = s.product_id
        ORDER BY s.sale_date DESC
        LIMIT 10
    ");
    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تنسيق التاريخ والوقت
    foreach ($sales as &$sale) {
        $sale['sale_date'] = date('Y-m-d H:i', strtotime($sale['sale_date']));
        $sale['price'] = number_format($sale['price'], 2);
    }
    
    echo json_encode($sales);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
