<?php
// api-orders.php - GET orders list for dashboard
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(['status' => 'error', 'message' => 'GET only'], 405);
}

requireAdmin();
$db = getDB();

$date = $_GET['date'] ?? date('Y-m-d');
$page = max(1, (int)($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

try {
    // Count
    $stmt = $db->prepare('SELECT COUNT(*) as total FROM orders WHERE DATE(created_at) = ?');
    $stmt->execute([$date]);
    $total = (int)$stmt->fetch()['total'];

    // Orders — LIMIT/OFFSET di-interpolasi langsung (sudah integer, aman)
    $stmt = $db->prepare('
        SELECT o.*, (
            SELECT GROUP_CONCAT(CONCAT(oi.product_name, " x", oi.quantity) SEPARATOR ", ")
            FROM order_items oi WHERE oi.order_id = o.id
        ) AS items_summary
        FROM orders o
        WHERE DATE(o.created_at) = ?
        ORDER BY o.created_at DESC
        LIMIT ' . $limit . ' OFFSET ' . $offset
    );
    $stmt->execute([$date]);
    $orders = $stmt->fetchAll();

    // Summary
    $stmt = $db->prepare("
        SELECT
            COUNT(*) as order_count,
            COALESCE(SUM(CASE WHEN status = 'refund' THEN 0 ELSE total END), 0) as total_revenue,
            COALESCE(SUM(CASE WHEN status = 'refund' THEN total ELSE 0 END), 0) as total_refund,
            SUM(CASE WHEN status = 'refund' THEN 1 ELSE 0 END) as refund_count,
            COALESCE(SUM(payment_amount), 0) as total_paid
        FROM orders WHERE DATE(created_at) = ?
    ");
    $stmt->execute([$date]);
    $summary = $stmt->fetch();

    // Per-outlet summary
    try {
        $outletStmt = $db->prepare('
            SELECT o.id AS outlet_id, o.name AS outlet_name,
                   COALESCE(SUM(CASE WHEN ord.status = \'refund\' THEN 0 ELSE ord.total END), 0) AS total_revenue,
                   COUNT(ord.id) AS order_count
            FROM outlets o
            LEFT JOIN orders ord ON ord.outlet_id = o.id AND DATE(ord.created_at) = ?
            GROUP BY o.id, o.name
            ORDER BY total_revenue DESC
        ');
        $outletStmt->execute([$date]);
        $outletsSummary = $outletStmt->fetchAll();
    } catch (Exception $e) {
        $outletsSummary = [];
    }

    jsonResponse([
        'status' => 'success',
        'data' => [
            'orders' => $orders,
            'summary' => $summary,
            'outlets_summary' => $outletsSummary,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'total_pages' => (int)ceil($total / $limit),
            ],
        ],
    ]);
} catch (Exception $e) {
    jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);
}