<?php

header('Content-Type: application/json');
$response = ['success' => false, 'chartData' => null, 'statusSummary' => null, 'message' => 'Gagal memuat data laporan.'];

require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../includes/session.php';
require_once __DIR__ . '/../../lib/Auth.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!Auth::isLoggedIn()) { http_response_code(401); $response['message'] = 'Sesi berakhir.'; echo json_encode($response); exit; }

if (!isset($pdo) || !$pdo instanceof PDO) { http_response_code(500); error_log("PDO object not available in get_order_report.php"); $response['message'] = 'Koneksi database gagal.'; echo json_encode($response); exit; }

try {

    $dateStartStr = $_GET['date_start'] ?? date('Y-m-d', strtotime('-6 days'));
    $dateEndStr = $_GET['date_end'] ?? date('Y-m-d');
    $userId = $_SESSION['user_id'];


    $dateStart = (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateStartStr)) ? $dateStartStr : null;
    $dateEnd = (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateEndStr)) ? $dateEndStr : null;

    if (!$dateStart || !$dateEnd) {
        throw new InvalidArgumentException("Format tanggal tidak valid.");
    }

    if (strtotime($dateEnd) < strtotime($dateStart)) {
         throw new InvalidArgumentException("Tanggal akhir tidak boleh sebelum tanggal mulai.");
    }

    $dateEndForQuery = $dateEnd . ' 23:59:59';

    $sqlChart = "SELECT DATE(created_at) as order_date, COUNT(id) as order_count
                 FROM orders
                 WHERE user_id = :user_id AND created_at >= :date_start AND created_at <= :date_end
                 GROUP BY DATE(created_at)
                 ORDER BY order_date ASC";
    $stmtChart = $pdo->prepare($sqlChart);
    $stmtChart->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtChart->bindParam(':date_start', $dateStart); 
    $stmtChart->bindParam(':date_end', $dateEndForQuery); 
    $stmtChart->execute();
    $dailyOrders = $stmtChart->fetchAll(PDO::FETCH_ASSOC);

    $chartLabels = [];
    $chartDataPoints = [];

    $currentDate = new DateTime($dateStart);
    $endDateObj = new DateTime($dateEnd);
    $interval = new DateInterval('P1D'); 
    $dateRange = new DatePeriod($currentDate, $interval, $endDateObj->modify('+1 day'));

    $ordersByDate = [];
    foreach ($dailyOrders as $row) {
        $ordersByDate[$row['order_date']] = $row['order_count'];
    }

    foreach ($dateRange as $date) {
        $formattedDate = $date->format('Y-m-d');
        $chartLabels[] = $formattedDate; 
        $chartDataPoints[] = $ordersByDate[$formattedDate] ?? 0; 
    }

    $chartData = [
        'labels' => $chartLabels,
        'datasets' => [
            [
                'label' => 'Jumlah Pesanan',
                'data' => $chartDataPoints,
                'borderColor' => 'rgb(59, 130, 246)', 
                'backgroundColor' => 'rgba(59, 130, 246, 0.1)',
                'tension' => 0.2, 
                'fill' => true,
            ]
        ]
    ];


    $sqlSummary = "SELECT status, COUNT(id) as count, SUM(price) as total_price
                   FROM orders
                   WHERE user_id = :user_id AND created_at >= :date_start AND created_at <= :date_end
                   GROUP BY status";
    $stmtSummary = $pdo->prepare($sqlSummary);
    $stmtSummary->bindParam(':user_id', $userId, PDO::PARAM_INT);
    $stmtSummary->bindParam(':date_start', $dateStart);
    $stmtSummary->bindParam(':date_end', $dateEndForQuery);
    $stmtSummary->execute();
    $statusSummaryRaw = $stmtSummary->fetchAll(PDO::FETCH_ASSOC);

    $statusSummary = [];
    $allStatuses = ['pending', 'processing', 'in progress', 'success', 'error', 'partial', 'canceled']; 
    $summaryMap = [];
    foreach ($statusSummaryRaw as $row) {
        $summaryMap[strtolower($row['status'])] = $row;
    }

    foreach ($allStatuses as $status) {
         $count = $summaryMap[$status]['count'] ?? 0;
         $total_price = $summaryMap[$status]['total_price'] ?? 0;
         $statusSummary[] = [
             'status' => ucfirst($status), 
             'status_key' => $status,
             'count' => (int)$count,
             'total_price' => (float)$total_price,
             'total_price_formatted' => 'Rp ' . number_format($total_price, 0, ',', '.')
         ];
    }

    $response['success'] = true;
    $response['chartData'] = $chartData;
    $response['statusSummary'] = $statusSummary;
    unset($response['message']);

} catch (InvalidArgumentException $e) {
    http_response_code(400); 
    $response['message'] = $e->getMessage();
} catch (\PDOException $e) {
    error_log("AJAX Get Order Report DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan database saat memuat laporan.";
    http_response_code(500);
} catch (\Throwable $e) {
    error_log("AJAX Get Order Report General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
