<?php
/**
 * Dashboard API Routes
 * 
 * Handles dashboard analytics and statistics.
 */

require_once '../lib/Auth.php';
require_once '../lib/Validation.php';

$auth = new Auth();
$validation = new Validation();
$response = new Response();
$db = getDB();

// Get request data
$input = json_decode(file_get_contents('php://input'), true) ?? [];
$action = $_GET['action'] ?? '';
$time_range = $_GET['range'] ?? 'today'; // today, week, month, year

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // Protect route - only authenticated users can access dashboard
        $user_data = $auth->protectRoute();
        
        switch ($action) {
            case 'stats':
                // Get dashboard statistics
                $stats = [];
                
                // Get date range for queries
                list($start_date, $end_date) = getDateRange($time_range);
                
                // Total revenue
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(total_amount), 0) as total_revenue 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats['total_revenue'] = floatval($stmt->fetch()['total_revenue']);
                
                // Total orders
                $stmt = $db->prepare("
                    SELECT COUNT(*) as total_orders 
                    FROM orders 
                    WHERE created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats['total_orders'] = intval($stmt->fetch()['total_orders']);
                
                // New customers
                $stmt = $db->prepare("
                    SELECT COUNT(*) as new_customers 
                    FROM users 
                    WHERE role = 'customer' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats['new_customers'] = intval($stmt->fetch()['new_customers']);
                
                // Total products
                $stmt = $db->prepare("SELECT COUNT(*) as total_products FROM products WHERE status = 'active'");
                $stmt->execute();
                $stats['total_products'] = intval($stmt->fetch()['total_products']);
                
                // Completed orders
                $stmt = $db->prepare("
                    SELECT COUNT(*) as completed_orders 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats['completed_orders'] = intval($stmt->fetch()['completed_orders']);
                
                // Pending orders
                $stmt = $db->prepare("
                    SELECT COUNT(*) as pending_orders 
                    FROM orders 
                    WHERE status = 'pending' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats['pending_orders'] = intval($stmt->fetch()['pending_orders']);
                
                // Average order value
                if ($stats['completed_orders'] > 0) {
                    $stats['average_order_value'] = $stats['total_revenue'] / $stats['completed_orders'];
                } else {
                    $stats['average_order_value'] = 0;
                }
                
                $response->success($stats);
                break;
                
            case 'revenue-chart':
                // Get revenue data for charts
                $chart_data = getRevenueChartData($time_range);
                $response->success($chart_data);
                break;
                
            case 'top-products':
                // Get top selling products
                $limit = min(10, max(1, intval($_GET['limit'] ?? 5)));
                
                $stmt = $db->prepare("
                    SELECT p.name, p.image_url, SUM(oi.quantity) as total_sold, SUM(oi.total_price) as total_revenue
                    FROM order_items oi
                    JOIN products p ON oi.product_id = p.id
                    JOIN orders o ON oi.order_id = o.id
                    WHERE o.status = 'completed'
                    GROUP BY p.id, p.name, p.image_url
                    ORDER BY total_sold DESC
                    LIMIT ?
                ");
                $stmt->execute([$limit]);
                $top_products = $stmt->fetchAll();
                
                $response->success($top_products);
                break;
                
            case 'recent-activity':
                // Get recent activity
                $limit = min(20, max(1, intval($_GET['limit'] ?? 10)));
                
                // Recent orders
                $stmt = $db->prepare("
                    SELECT o.*, u.name as customer_name 
                    FROM orders o 
                    LEFT JOIN users u ON o.customer_id = u.id 
                    ORDER BY o.created_at DESC 
                    LIMIT ?
                ");
                $stmt->execute([$limit]);
                $recent_orders = $stmt->fetchAll();
                
                // Recent payments
                $stmt = $db->prepare("
                    SELECT p.*, o.order_number, o.customer_name 
                    FROM payments p 
                    JOIN orders o ON p.order_id = o.id 
                    ORDER BY p.created_at DESC 
                    LIMIT ?
                ");
                $stmt->execute([$limit]);
                $recent_payments = $stmt->fetchAll();
                
                $response->success([
                    'recent_orders' => $recent_orders,
                    'recent_payments' => $recent_payments
                ]);
                break;
                
            case 'sales-by-category':
                // Get sales by product category
                $stmt = $db->prepare("
                    SELECT pc.name as category_name, COUNT(oi.id) as order_count, 
                           SUM(oi.quantity) as total_quantity, SUM(oi.total_price) as total_revenue
                    FROM order_items oi
                    JOIN products p ON oi.product_id = p.id
                    JOIN product_categories pc ON p.category_id = pc.id
                    JOIN orders o ON oi.order_id = o.id
                    WHERE o.status = 'completed'
                    GROUP BY pc.id, pc.name
                    ORDER BY total_revenue DESC
                ");
                $stmt->execute();
                $sales_by_category = $stmt->fetchAll();
                
                $response->success($sales_by_category);
                break;
                
            default:
                // Get comprehensive dashboard data
                list($start_date, $end_date) = getDateRange($time_range);
                
                // Basic stats
                $stmt = $db->prepare("
                    SELECT 
                        COUNT(*) as total_orders,
                        SUM(CASE WHEN status = 'completed' THEN total_amount ELSE 0 END) as total_revenue,
                        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_orders,
                        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders
                    FROM orders 
                    WHERE created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $stats = $stmt->fetch();
                
                // Customer stats
                $stmt = $db->prepare("
                    SELECT COUNT(*) as new_customers 
                    FROM users 
                    WHERE role = 'customer' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $customer_stats = $stmt->fetch();
                
                // Product stats
                $stmt = $db->prepare("SELECT COUNT(*) as total_products FROM products WHERE status = 'active'");
                $stmt->execute();
                $product_stats = $stmt->fetch();
                
                $dashboard_data = array_merge($stats, $customer_stats, $product_stats);
                
                // Convert to proper types
                $dashboard_data['total_orders'] = intval($dashboard_data['total_orders']);
                $dashboard_data['total_revenue'] = floatval($dashboard_data['total_revenue']);
                $dashboard_data['completed_orders'] = intval($dashboard_data['completed_orders']);
                $dashboard_data['pending_orders'] = intval($dashboard_data['pending_orders']);
                $dashboard_data['new_customers'] = intval($dashboard_data['new_customers']);
                $dashboard_data['total_products'] = intval($dashboard_data['total_products']);
                
                if ($dashboard_data['completed_orders'] > 0) {
                    $dashboard_data['average_order_value'] = $dashboard_data['total_revenue'] / $dashboard_data['completed_orders'];
                } else {
                    $dashboard_data['average_order_value'] = 0;
                }
                
                $response->success($dashboard_data);
                break;
        }
        break;
        
    default:
        $response->error('Method not allowed', 405);
        break;
}

/**
 * Get date range based on time range parameter
 */
function getDateRange($range) {
    $end_date = date('Y-m-d 23:59:59');
    
    switch ($range) {
        case 'week':
            $start_date = date('Y-m-d 00:00:00', strtotime('-7 days'));
            break;
        case 'month':
            $start_date = date('Y-m-d 00:00:00', strtotime('-1 month'));
            break;
        case 'year':
            $start_date = date('Y-m-d 00:00:00', strtotime('-1 year'));
            break;
        case 'today':
        default:
            $start_date = date('Y-m-d 00:00:00');
            break;
    }
    
    return [$start_date, $end_date];
}

/**
 * Generate revenue chart data
 */
function getRevenueChartData($range) {
    global $db;
    
    $data = [];
    
    switch ($range) {
        case 'year':
            // Monthly data for the year
            $current_year = date('Y');
            for ($month = 1; $month <= 12; $month++) {
                $start_date = date('Y-m-d 00:00:00', strtotime("$current_year-$month-01"));
                $end_date = date('Y-m-d 23:59:59', strtotime("$current_year-$month-01 +1 month -1 day"));
                
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(total_amount), 0) as revenue 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $result = $stmt->fetch();
                
                $data[] = [
                    'period' => date('M Y', strtotime($start_date)),
                    'revenue' => floatval($result['revenue']),
                    'orders' => 0 // You can add order count if needed
                ];
            }
            break;
            
        case 'month':
            // Daily data for the month
            $current_month = date('Y-m');
            $days_in_month = date('t');
            
            for ($day = 1; $day <= $days_in_month; $day++) {
                $date = date('Y-m-d', strtotime("$current_month-$day"));
                $start_date = $date . ' 00:00:00';
                $end_date = $date . ' 23:59:59';
                
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(total_amount), 0) as revenue 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $result = $stmt->fetch();
                
                $data[] = [
                    'period' => date('M j', strtotime($date)),
                    'revenue' => floatval($result['revenue']),
                    'orders' => 0
                ];
            }
            break;
            
        case 'week':
            // Daily data for the week
            for ($day = 6; $day >= 0; $day--) {
                $date = date('Y-m-d', strtotime("-$day days"));
                $start_date = $date . ' 00:00:00';
                $end_date = $date . ' 23:59:59';
                
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(total_amount), 0) as revenue 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $result = $stmt->fetch();
                
                $data[] = [
                    'period' => date('D', strtotime($date)),
                    'revenue' => floatval($result['revenue']),
                    'orders' => 0
                ];
            }
            break;
            
        case 'today':
        default:
            // Hourly data for today
            for ($hour = 0; $hour < 24; $hour++) {
                $start_date = date('Y-m-d ') . sprintf('%02d:00:00', $hour);
                $end_date = date('Y-m-d ') . sprintf('%02d:59:59', $hour);
                
                $stmt = $db->prepare("
                    SELECT COALESCE(SUM(total_amount), 0) as revenue 
                    FROM orders 
                    WHERE status = 'completed' 
                    AND created_at BETWEEN ? AND ?
                ");
                $stmt->execute([$start_date, $end_date]);
                $result = $stmt->fetch();
                
                $data[] = [
                    'period' => sprintf('%02d:00', $hour),
                    'revenue' => floatval($result['revenue']),
                    'orders' => 0
                ];
            }
            break;
    }
    
    return $data;
}