<?php
/**
 * API endpoint لجلب الإحصائيات
 */
session_start();
require 'config.php';
require 'analytics_service.php';

header('Content-Type: application/json; charset=UTF-8');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['status' => 'error', 'message' => 'غير مسموح']);
    exit;
}

$deviceId = $_GET['device_id'] ?? null;
$startDate = $_GET['start_date'] ?? date('Y-m-d') . ' 00:00:00';
$endDate = $_GET['end_date'] ?? date('Y-m-d') . ' 23:59:59';
$period = $_GET['period'] ?? 'day'; // day, week, month

if (!$deviceId) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'device_id مطلوب']);
    exit;
}

$analyticsService = new AnalyticsService($conn, $_SESSION['user_id']);

if ($period === 'daily') {
    $days = isset($_GET['days']) ? (int)$_GET['days'] : 7;
    $stats = $analyticsService->getDailyStatistics($deviceId, $days);
} else {
    $stats = $analyticsService->getDeviceStatistics($deviceId, $startDate, $endDate);
}

echo json_encode([
    'status' => 'success',
    'data' => $stats
], JSON_UNESCAPED_UNICODE);

