<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';

if (!User::isLoggedIn() || !User::isAdmin()) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit();
}

$section = $_GET['section'] ?? '';

if (empty($section)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Section parameter is required']);
    exit();
}

try {
    $pdo = getDBConnection();
    $today = date('Y-m-d');
    $week_start = date('Y-m-d', strtotime('monday this week'));
    $month_start = date('Y-m-d', strtotime('first day of this month'));
    
    switch ($section) {
        case 'orders':
            $stmt = $pdo->prepare("
                SELECT o.*, 
                       COALESCE(o.customer_name, u.name) as customer_name,
                       GROUP_CONCAT(s.name SEPARATOR ', ') as service_names,
                       GROUP_CONCAT(oi.quantity SEPARATOR ', ') as quantities
                FROM orders o 
                LEFT JOIN users u ON o.user_id = u.id 
                LEFT JOIN order_items oi ON o.id = oi.order_id
                LEFT JOIN services s ON oi.service_id = s.id
                GROUP BY o.id
                ORDER BY o.created_at DESC
            ");
            $stmt->execute();
            $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'orders' => $orders
            ]);
            break;
            
        case 'offers':
            $stmt = $pdo->prepare("UPDATE offers SET status = 'expired' WHERE end_date < CURDATE() AND status = 'active'");
            $stmt->execute();
            
            $stmt = $pdo->prepare("
                SELECT *, 
                       CASE 
                           WHEN end_date < CURDATE() THEN 'expired'
                           WHEN start_date > CURDATE() THEN 'pending'
                           WHEN start_date <= CURDATE() AND end_date >= CURDATE() THEN status
                           ELSE status
                       END as computed_status,
                       COALESCE(used_count, 0) as used_count
                FROM offers 
                ORDER BY 
                    CASE status 
                        WHEN 'active' THEN 1 
                        WHEN 'inactive' THEN 2 
                        WHEN 'expired' THEN 3 
                        ELSE 4 
                    END,
                    created_at DESC
            ");
            $stmt->execute();
            $offers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $active_offers = 0;
            $inactive_offers = 0;
            $expired_offers = 0;
            $total_offers = count($offers);
            
            foreach ($offers as $offer) {
                $status = $offer['computed_status'];
                if ($status === 'active' && strtotime($offer['start_date']) <= time() && strtotime($offer['end_date']) >= time()) {
                    $active_offers++;
                } elseif ($status === 'inactive') {
                    $inactive_offers++;
                } elseif ($status === 'expired' || strtotime($offer['end_date']) < time()) {
                    $expired_offers++;
                }
            }
            
            echo json_encode([
                'success' => true,
                'offers' => $offers,
                'stats' => [
                    'active_offers' => $active_offers,
                    'total_offers' => $total_offers,
                    'inactive_offers' => $inactive_offers,
                    'expired_offers' => $expired_offers
                ]
            ]);
            break;
            
        case 'customers':
            $stmt = $pdo->prepare("
                SELECT u.*, 
                       COUNT(o.id) as order_count,
                       COALESCE(SUM(CASE WHEN o.status = 'completed' THEN o.total_amount ELSE 0 END), 0) as total_spent,
                       CASE 
                           WHEN EXISTS(SELECT 1 FROM subscriptions s WHERE s.user_id = u.id AND s.status = 'active') THEN 'Subscribed'
                           WHEN COUNT(o.id) >= 5 THEN 'Regular'
                           WHEN COUNT(o.id) > 0 THEN 'Normal'
                           ELSE 'New'
                       END as customer_type,
                       COALESCE(MAX(o.created_at), u.created_at) as last_activity
                FROM users u 
                LEFT JOIN orders o ON u.id = o.user_id 
                GROUP BY u.id 
                ORDER BY u.created_at DESC
            ");
            $stmt->execute();
            $customers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT COUNT(DISTINCT user_id) as count FROM orders WHERE DATE(created_at) >= ?");
            $stmt->execute([$week_start]);
            $active_customers = $stmt->fetch()['count'];
            
            echo json_encode([
                'success' => true,
                'customers' => $customers,
                'stats' => [
                    'active_customers' => $active_customers,
                    'total_customers' => count($customers)
                ]
            ]);
            break;
            
        case 'reviews':
            $stmt = $pdo->prepare("
                SELECT r.*, u.name as customer_name, o.id as order_number, o.total_amount
                FROM reviews r 
                LEFT JOIN users u ON r.user_id = u.id 
                LEFT JOIN orders o ON r.order_id = o.id 
                ORDER BY r.created_at DESC 
                LIMIT 50
            ");
            $stmt->execute();
            $reviews = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("SELECT AVG(rating) as avg_rating, COUNT(*) as total_reviews FROM reviews");
            $stmt->execute();
            $review_stats = $stmt->fetch();
            
            echo json_encode([
                'success' => true,
                'reviews' => $reviews,
                'stats' => [
                    'avg_rating' => $review_stats['avg_rating'],
                    'total_reviews' => $review_stats['total_reviews']
                ]
            ]);
            break;
            
        case 'subscriptions':
            $stmt = $pdo->prepare("
                SELECT s.*, u.name as customer_name, u.email as customer_email,
                       DATEDIFF(s.end_date, CURDATE()) as days_left
                FROM subscriptions s 
                LEFT JOIN users u ON s.user_id = u.id 
                WHERE s.status = 'active' 
                ORDER BY s.end_date ASC
            ");
            $stmt->execute();
            $subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $active_subscriptions = count($subscriptions);
            
            echo json_encode([
                'success' => true,
                'subscriptions' => $subscriptions,
                'stats' => [
                    'active_subscriptions' => $active_subscriptions
                ]
            ]);
            break;
            
        case 'delivery':
            $stmt = $pdo->prepare("
                SELECT * FROM delivery_staff 
                ORDER BY status, total_deliveries DESC
            ");
            $stmt->execute();
            $delivery_staff = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $available_staff = count(array_filter($delivery_staff, function($staff) { 
                return $staff['status'] == 'available'; 
            }));
            
            $total_staff = count($delivery_staff);
            
            $stmt = $pdo->prepare("
                SELECT AVG(average_delivery_time) as avg_time 
                FROM delivery_staff 
                WHERE status != 'offline'
            ");
            $stmt->execute();
            $avg_delivery_time = $stmt->fetch()['avg_time'] ?? 0;
            
            echo json_encode([
                'success' => true,
                'delivery_staff' => $delivery_staff,
                'stats' => [
                    'available_staff' => $available_staff,
                    'total_staff' => $total_staff,
                    'avg_delivery_time' => $avg_delivery_time
                ]
            ]);
            break;
            
        case 'financial':
            $stmt = $pdo->prepare("SELECT SUM(total_amount) as total_revenue FROM orders WHERE status = 'completed'");
            $stmt->execute();
            $total_revenue = $stmt->fetch()['total_revenue'] ?? 0;
            
            $stmt = $pdo->prepare("SELECT SUM(price) as subscription_revenue FROM subscriptions WHERE status = 'active'");
            $stmt->execute();
            $subscription_revenue = $stmt->fetch()['subscription_revenue'] ?? 0;
            
            $stmt = $pdo->prepare("SELECT SUM(amount) as total_expenses FROM expenses WHERE expense_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
            $stmt->execute();
            $total_expenses = $stmt->fetch()['total_expenses'] ?? 0;
            
            $net_profit = $total_revenue - $total_expenses;
            
            $stmt = $pdo->prepare("
                SELECT category, SUM(amount) as total_amount, COUNT(*) as count
                FROM expenses 
                WHERE expense_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                GROUP BY category 
                ORDER BY total_amount DESC
            ");
            $stmt->execute();
            $expense_categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $stmt = $pdo->prepare("
                SELECT s.name, s.category, 
                       COUNT(oi.id) as order_count,
                       SUM(oi.quantity) as total_quantity,
                       SUM(oi.price * oi.quantity) as total_revenue
                FROM services s
                LEFT JOIN order_items oi ON s.id = oi.service_id
                LEFT JOIN orders o ON oi.order_id = o.id AND o.status = 'completed'
                GROUP BY s.id, s.name, s.category
                ORDER BY total_revenue DESC
            ");
            $stmt->execute();
            $service_stats = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'stats' => [
                    'total_revenue' => $total_revenue,
                    'subscription_revenue' => $subscription_revenue,
                    'total_expenses' => $total_expenses,
                    'net_profit' => $net_profit
                ],
                'expense_categories' => $expense_categories,
                'service_stats' => $service_stats
            ]);
            break;
            
        case 'notifications':
            $stmt = $pdo->prepare("
                SELECT * FROM notifications 
                WHERE is_read = FALSE 
                ORDER BY created_at DESC 
                LIMIT 10
            ");
            $stmt->execute();
            $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            $system_notifications = [];
            
            if (empty($notifications)) {
                $stmt = $pdo->prepare("
                    SELECT COUNT(*) as count 
                    FROM orders 
                    WHERE status IN ('pending', 'processing') 
                    AND created_at < DATE_SUB(NOW(), INTERVAL 3 DAY)
                ");
                $stmt->execute();
                $overdue_orders = $stmt->fetch()['count'];
                
                if ($overdue_orders > 0) {
                    $system_notifications[] = [
                        'type' => 'warning',
                        'title' => 'Overdue Orders',
                        'message' => "There are {$overdue_orders} overdue orders",
                        'time' => 'Now'
                    ];
                }
                
                $stmt = $pdo->prepare("
                    SELECT COUNT(*) as count 
                    FROM subscriptions s 
                    LEFT JOIN users u ON s.user_id = u.id 
                    WHERE s.status = 'active' 
                    AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
                ");
                $stmt->execute();
                $expiring_subs = $stmt->fetch()['count'];
                
                if ($expiring_subs > 0) {
                    $system_notifications[] = [
                        'type' => 'warning',
                        'title' => 'Expiring Subscriptions',
                        'message' => "{$expiring_subs} subscription(s) will expire within 3 days",
                        'time' => 'Now'
                    ];
                }
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM contact_messages WHERE status = 'new'");
                $stmt->execute();
                $new_messages = $stmt->fetch()['count'];
                
                if ($new_messages > 0) {
                    $system_notifications[] = [
                        'type' => 'info',
                        'title' => 'New Messages',
                        'message' => "There are {$new_messages} new messages from customers",
                        'time' => 'Now'
                    ];
                }
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = ?");
                $stmt->execute([$today]);
                $new_customers_today = $stmt->fetch()['count'];
                
                if ($new_customers_today > 0) {
                    $system_notifications[] = [
                        'type' => 'success',
                        'title' => 'New Customers',
                        'message' => "{$new_customers_today} new customers registered today",
                        'time' => 'Today'
                    ];
                }
                
                $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM orders WHERE DATE(created_at) = ?");
                $stmt->execute([$today]);
                $orders_today = $stmt->fetch()['count'];
                
                if ($orders_today > 0) {
                    $system_notifications[] = [
                        'type' => 'info',
                        'title' => 'New Orders',
                        'message' => "{$orders_today} new orders received today",
                        'time' => 'Today'
                    ];
                }
            }
            
            echo json_encode([
                'success' => true,
                'notifications' => $notifications,
                'system_notifications' => $system_notifications
            ]);
            break;
            
        default:
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => 'Invalid section parameter'
            ]);
            break;
    }
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
