<?php
require_once '../config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendResponse(false, 'Only GET method allowed', null, 405);
}

try {
    $user = validateToken($conn);
    
    // Get dashboard statistics
    $stats = [];
    
    // Total products
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM products");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_products'] = $result->fetch_assoc()['total'];
    
    // Total customers (permanent + temporary)
    $stmt = $conn->prepare("SELECT (SELECT COUNT(*) FROM permanentcustomer) + (SELECT COUNT(*) FROM customers) as total");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_customers'] = $result->fetch_assoc()['total'];
    
    // Total invoices
    $stmt = $conn->prepare("SELECT COUNT(*) as total FROM invoices");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_invoices'] = $result->fetch_assoc()['total'];
    
    // Total revenue
    $stmt = $conn->prepare("SELECT SUM(total_amount) as total FROM invoices WHERE status = 'completed'");
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['total_revenue'] = $result->fetch_assoc()['total'] ?: 0;
    
    // Recent invoices (last 10)
    $stmt = $conn->prepare("
        SELECT 
            i.*,
            CASE 
                WHEN i.customer_type = 'permanent' THEN p.name
                ELSE c.name
            END as customer_name
        FROM invoices i
        LEFT JOIN permanentcustomer p ON i.customer_id = p.id AND i.customer_type = 'permanent'
        LEFT JOIN customers c ON i.customer_id = c.id AND i.customer_type = 'temporary'
        ORDER BY i.created_at DESC
        LIMIT 10
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $recent_invoices = [];
    while ($row = $result->fetch_assoc()) {
        $recent_invoices[] = $row;
    }
    $stats['recent_invoices'] = $recent_invoices;
    
    // Low stock products (quantity < 10)
    $stmt = $conn->prepare("SELECT * FROM products WHERE quantity < 10 ORDER BY quantity ASC LIMIT 10");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $low_stock = [];
    while ($row = $result->fetch_assoc()) {
        $row['images'] = json_decode($row['images'], true) ?: [];
        $low_stock[] = $row;
    }
    $stats['low_stock_products'] = $low_stock;
    
    // Monthly revenue (last 6 months)
    $stmt = $conn->prepare("
        SELECT 
            DATE_FORMAT(created_at, '%Y-%m') as month,
            SUM(total_amount) as revenue,
            COUNT(*) as invoice_count
        FROM invoices 
        WHERE status = 'completed' 
        AND created_at >= DATE_SUB(NOW(), INTERVAL 6 MONTH)
        GROUP BY DATE_FORMAT(created_at, '%Y-%m')
        ORDER BY month ASC
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $monthly_revenue = [];
    while ($row = $result->fetch_assoc()) {
        $monthly_revenue[] = $row;
    }
    $stats['monthly_revenue'] = $monthly_revenue;
    
    // Top selling products (last 30 days)
    $stmt = $conn->prepare("
        SELECT 
            p.id,
            p.name,
            p.sell_price,
            p.images,
            SUM(ii.quantity) as total_sold,
            SUM(ii.quantity * ii.price) as total_revenue
        FROM invoice_items ii
        JOIN invoices i ON ii.invoice_id = i.id
        JOIN products p ON ii.product_id = p.id
        WHERE i.status = 'completed'
        AND i.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
        GROUP BY p.id
        ORDER BY total_sold DESC
        LIMIT 10
    ");
    $stmt->execute();
    $result = $stmt->get_result();
    
    $top_products = [];
    while ($row = $result->fetch_assoc()) {
        $row['images'] = json_decode($row['images'], true) ?: [];
        $top_products[] = $row;
    }
    $stats['top_selling_products'] = $top_products;
    
    sendResponse(true, 'Dashboard statistics retrieved successfully', $stats);
    
} catch (Exception $e) {
    sendResponse(false, 'Failed to get dashboard statistics: ' . $e->getMessage(), null, 500);
}
?>
