<?php
/**
 * advanced_reports.php - نظام التقارير الاحترافي المتكامل
 * @version 9.0.0 - النسخة النهائية مع تحميل مباشر
 */

require_once 'config.php';
checkAdminAuth();

// ============================================
// معالجة الفلاتر
// ============================================
$report_type = $_GET['report_type'] ?? 'cashier';
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$entity_id = isset($_GET['entity_id']) ? (int)$_GET['entity_id'] : 0;

// ============================================
// جلب البيانات للقوائم المنسدلة
// ============================================

// الكاشير
$cashiers = $conn->query("SELECT id, name, phone, branch FROM cashiers WHERE status = 'active' ORDER BY name");

// الكباتن
$captains = $conn->query("SELECT id, name, phone, vehicle_info FROM captains WHERE status = 'active' ORDER BY name");

// العملاء
$customers = $conn->query("SELECT id, name, phone, address FROM customers ORDER BY name LIMIT 200");

// الوجبات
$meals = $conn->query("SELECT m.id, m.name, c.name as category, m.price FROM meals m LEFT JOIN categories c ON m.category_id = c.id WHERE m.is_active = 1 ORDER BY m.name");

// التصنيفات
$categories = $conn->query("SELECT id, name FROM categories ORDER BY name");

// جلب اسم الكاشير المحدد
$cashier_name = '';
if ($report_type == 'cashier' && $entity_id > 0) {
    $cashier_result = $conn->query("SELECT name FROM cashiers WHERE id = $entity_id");
    if ($cashier_result && $cashier_result->num_rows > 0) {
        $cashier_name = $cashier_result->fetch_assoc()['name'];
    }
}

// جلب اسم الكابتن المحدد
$captain_name = '';
if ($report_type == 'captain' && $entity_id > 0) {
    $captain_result = $conn->query("SELECT name FROM captains WHERE id = $entity_id");
    if ($captain_result && $captain_result->num_rows > 0) {
        $captain_name = $captain_result->fetch_assoc()['name'];
    }
}

// ============================================
// إحصائيات عامة للفترة
// ============================================
$global_stats = $conn->query("
    SELECT 
        COUNT(DISTINCT o.id) as total_orders,
        COALESCE(SUM(o.total), 0) as total_revenue,
        COALESCE(AVG(o.total), 0) as avg_order,
        COUNT(DISTINCT o.customer_id) as unique_customers,
        COUNT(DISTINCT o.captain_id) as active_captains,
        COUNT(DISTINCT o.cashier_id) as active_cashiers,
        SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) as completed_orders
    FROM orders o
    WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
")->fetch_assoc();

// ============================================
// دوال جلب التقارير
// ============================================

function getCashierReport($conn, $start_date, $end_date, $cashier_id = 0) {
    $filter = $cashier_id ? "AND o.cashier_id = $cashier_id" : "";
    
    $summary = $conn->query("
        SELECT 
            COUNT(DISTINCT o.id) as total_orders,
            COALESCE(SUM(o.total), 0) as total_revenue,
            COALESCE(AVG(o.total), 0) as avg_order,
            COUNT(DISTINCT o.customer_id) as unique_customers,
            SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) as completed_orders,
            SUM(CASE WHEN o.payment_method = 'cash' THEN o.total ELSE 0 END) as cash_revenue,
            SUM(CASE WHEN o.payment_method = 'card' THEN o.total ELSE 0 END) as card_revenue
        FROM orders o
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        $filter
    ")->fetch_assoc();
    
    $details = $conn->query("
        SELECT 
            c.id,
            c.name,
            c.phone,
            c.branch,
            COUNT(DISTINCT o.id) as orders_count,
            COALESCE(SUM(o.total), 0) as total_revenue,
            ROUND(AVG(o.total), 2) as avg_order,
            COUNT(DISTINCT o.customer_id) as customers_served,
            SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) as completed,
            SUM(CASE WHEN o.payment_method = 'cash' THEN o.total ELSE 0 END) as cash_amount,
            SUM(CASE WHEN o.payment_method = 'card' THEN o.total ELSE 0 END) as card_amount
        FROM cashiers c
        LEFT JOIN orders o ON c.id = o.cashier_id 
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        GROUP BY c.id, c.name, c.phone, c.branch
        HAVING orders_count > 0
        ORDER BY total_revenue DESC
    ");
    
    return ['summary' => $summary, 'details' => $details];
}

function getCaptainReport($conn, $start_date, $end_date, $captain_id = 0) {
    $filter = $captain_id ? "AND o.captain_id = $captain_id" : "";
    
    $summary = $conn->query("
        SELECT 
            COUNT(DISTINCT o.id) as total_deliveries,
            COALESCE(SUM(o.total), 0) as total_revenue,
            COALESCE(AVG(o.total), 0) as avg_order,
            COUNT(DISTINCT o.customer_id) as unique_customers,
            SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) as completed,
            ROUND(AVG(TIMESTAMPDIFF(MINUTE, o.accepted_at, o.delivered_at)), 0) as avg_delivery_time
        FROM orders o
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        AND o.captain_id IS NOT NULL
        $filter
    ")->fetch_assoc();
    
    $details = $conn->query("
        SELECT 
            cp.id,
            cp.name,
            cp.phone,
            cp.vehicle_info,
            COUNT(DISTINCT o.id) as deliveries_count,
            COALESCE(SUM(o.total), 0) as total_revenue,
            ROUND(AVG(o.total), 2) as avg_order,
            COUNT(DISTINCT o.customer_id) as customers_served,
            SUM(CASE WHEN o.status = 'delivered' THEN 1 ELSE 0 END) as completed,
            COUNT(DISTINCT DATE(o.created_at)) as working_days
        FROM captains cp
        LEFT JOIN orders o ON cp.id = o.captain_id 
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        GROUP BY cp.id, cp.name, cp.phone, cp.vehicle_info
        HAVING deliveries_count > 0
        ORDER BY total_revenue DESC
    ");
    
    return ['summary' => $summary, 'details' => $details];
}

function getCustomerReport($conn, $start_date, $end_date, $customer_id = 0) {
    $filter = $customer_id ? "AND o.customer_id = $customer_id" : "";
    
    $summary = $conn->query("
        SELECT 
            COUNT(DISTINCT o.id) as total_orders,
            COALESCE(SUM(o.total), 0) as total_spent,
            COALESCE(AVG(o.total), 0) as avg_order,
            MAX(o.total) as max_order,
            COUNT(DISTINCT o.captain_id) as different_captains
        FROM orders o
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        $filter
    ")->fetch_assoc();
    
    $details = $conn->query("
        SELECT 
            c.id,
            c.name,
            c.phone,
            c.address,
            COUNT(DISTINCT o.id) as orders_count,
            COALESCE(SUM(o.total), 0) as total_spent,
            ROUND(AVG(o.total), 2) as avg_order,
            MAX(o.total) as max_order,
            MAX(o.created_at) as last_order_date,
            DATEDIFF(NOW(), MAX(o.created_at)) as days_since_last,
            COUNT(DISTINCT o.captain_id) as captains_used
        FROM customers c
        LEFT JOIN orders o ON c.id = o.customer_id 
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        GROUP BY c.id, c.name, c.phone, c.address
        HAVING orders_count > 0
        ORDER BY total_spent DESC
        LIMIT 100
    ");
    
    return ['summary' => $summary, 'details' => $details];
}

function getMealReport($conn, $start_date, $end_date, $meal_id = 0) {
    $filter = $meal_id ? "AND m.id = $meal_id" : "";
    
    $total_revenue = $conn->query("
        SELECT COALESCE(SUM(oi.quantity * oi.price), 0) as total
        FROM order_items oi
        JOIN orders o ON oi.order_id = o.id
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
    ")->fetch_assoc()['total'];
    
    $summary = $conn->query("
        SELECT 
            COUNT(DISTINCT m.id) as meals_sold,
            SUM(oi.quantity) as total_items_sold,
            COALESCE(SUM(oi.quantity * oi.price), 0) as total_revenue,
            COUNT(DISTINCT oi.order_id) as total_orders,
            ROUND(SUM(oi.quantity) / NULLIF(COUNT(DISTINCT oi.order_id), 0), 1) as avg_items_per_order
        FROM meals m
        LEFT JOIN order_items oi ON m.id = oi.meal_id
        LEFT JOIN orders o ON oi.order_id = o.id
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        WHERE m.is_active = 1
    ")->fetch_assoc();
    
    $details = $conn->query("
        SELECT 
            m.id,
            m.name,
            COALESCE(cat.name, 'غير مصنف') as category,
            m.price as unit_price,
            COALESCE(SUM(oi.quantity), 0) as quantity_sold,
            COALESCE(SUM(oi.quantity * oi.price), 0) as total_revenue,
            COUNT(DISTINCT oi.order_id) as orders_count,
            ROUND(COALESCE(SUM(oi.quantity * oi.price), 0) / NULLIF($total_revenue, 0) * 100, 1) as revenue_percent,
            CASE 
                WHEN COALESCE(SUM(oi.quantity * oi.price), 0) / NULLIF($total_revenue, 0) * 100 >= 20 THEN 'A'
                WHEN COALESCE(SUM(oi.quantity * oi.price), 0) / NULLIF($total_revenue, 0) * 100 >= 10 THEN 'B'
                WHEN COALESCE(SUM(oi.quantity * oi.price), 0) / NULLIF($total_revenue, 0) * 100 >= 5 THEN 'C'
                ELSE 'D'
            END as abc_class
        FROM meals m
        LEFT JOIN categories cat ON m.category_id = cat.id
        LEFT JOIN order_items oi ON m.id = oi.meal_id
        LEFT JOIN orders o ON oi.order_id = o.id 
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        WHERE m.is_active = 1
        GROUP BY m.id, m.name, cat.name, m.price
        HAVING quantity_sold > 0
        ORDER BY total_revenue DESC
    ");
    
    return ['summary' => $summary, 'details' => $details];
}

function getCategoryReport($conn, $start_date, $end_date, $category_id = 0) {
    $filter = $category_id ? "AND cat.id = $category_id" : "";
    
    $total_revenue = $conn->query("
        SELECT COALESCE(SUM(oi.quantity * oi.price), 0) as total
        FROM order_items oi
        JOIN orders o ON oi.order_id = o.id
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
    ")->fetch_assoc()['total'];
    
    $summary = $conn->query("
        SELECT 
            COUNT(DISTINCT cat.id) as active_categories,
            COUNT(DISTINCT m.id) as meals_count,
            COALESCE(SUM(oi.quantity), 0) as total_items,
            COALESCE(SUM(oi.quantity * oi.price), 0) as total_revenue,
            COUNT(DISTINCT o.id) as total_orders
        FROM categories cat
        LEFT JOIN meals m ON cat.id = m.category_id
        LEFT JOIN order_items oi ON m.id = oi.meal_id
        LEFT JOIN orders o ON oi.order_id = o.id
        WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
    ")->fetch_assoc();
    
    $details = $conn->query("
        SELECT 
            cat.id,
            cat.name,
            COUNT(DISTINCT m.id) as meals_count,
            COALESCE(SUM(oi.quantity), 0) as quantity_sold,
            COALESCE(SUM(oi.quantity * oi.price), 0) as total_revenue,
            COUNT(DISTINCT o.id) as orders_count,
            ROUND(COALESCE(SUM(oi.quantity * oi.price), 0) / NULLIF($total_revenue, 0) * 100, 1) as revenue_share,
            (
                SELECT m2.name
                FROM meals m2
                LEFT JOIN order_items oi2 ON m2.id = oi2.meal_id
                LEFT JOIN orders o2 ON oi2.order_id = o2.id
                WHERE m2.category_id = cat.id
                    AND DATE(o2.created_at) BETWEEN '$start_date' AND '$end_date'
                GROUP BY m2.id, m2.name
                ORDER BY SUM(oi2.quantity * oi2.price) DESC
                LIMIT 1
            ) as top_meal
        FROM categories cat
        LEFT JOIN meals m ON cat.id = m.category_id AND m.is_active = 1
        LEFT JOIN order_items oi ON m.id = oi.meal_id
        LEFT JOIN orders o ON oi.order_id = o.id 
            AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        GROUP BY cat.id, cat.name
        HAVING quantity_sold > 0
        ORDER BY total_revenue DESC
    ");
    
    return ['summary' => $summary, 'details' => $details];
}

// ============================================
// جلب البيانات حسب نوع التقرير
// ============================================
$report_data = null;
$report_title = '';
$report_icon = '';
$summary_labels = [];
$details_columns = [];

switch($report_type) {
    case 'cashier':
        $report_title = 'تقرير أداء الكاشير';
        $report_icon = 'bi-person-workspace';
        $report_data = getCashierReport($conn, $start_date, $end_date, $entity_id);
        $summary_labels = [
            'total_orders' => 'إجمالي الطلبات',
            'total_revenue' => 'الإيرادات',
            'avg_order' => 'متوسط الطلب',
            'unique_customers' => 'عملاء',
            'completed_orders' => 'مكتمل',
            'cash_revenue' => 'نقدي',
            'card_revenue' => 'بطاقة'
        ];
        $details_columns = ['الكاشير', 'الفرع', 'الطلبات', 'الإيرادات', 'المتوسط', 'مكتمل', 'نقدي', 'بطاقة', 'العملاء'];
        break;
        
    case 'captain':
        $report_title = 'تقرير أداء الكباتن';
        $report_icon = 'bi-truck';
        $report_data = getCaptainReport($conn, $start_date, $end_date, $entity_id);
        $summary_labels = [
            'total_deliveries' => 'إجمالي التوصيلات',
            'total_revenue' => 'الإيرادات',
            'avg_order' => 'متوسط الطلب',
            'unique_customers' => 'عملاء',
            'completed' => 'مكتمل',
            'avg_delivery_time' => 'متوسط وقت التوصيل'
        ];
        $details_columns = ['الكابتن', 'الهاتف', 'المركبة', 'التوصيلات', 'الإيرادات', 'المتوسط', 'مكتمل', 'أيام العمل', 'العملاء'];
        break;
        
    case 'customer':
        $report_title = 'تقرير العملاء';
        $report_icon = 'bi-people';
        $report_data = getCustomerReport($conn, $start_date, $end_date, $entity_id);
        $summary_labels = [
            'total_orders' => 'إجمالي الطلبات',
            'total_spent' => 'إجمالي المشتريات',
            'avg_order' => 'متوسط الطلب',
            'max_order' => 'أكبر طلب',
            'different_captains' => 'كباتن مختلفين'
        ];
        $details_columns = ['العميل', 'الهاتف', 'الطلبات', 'المشتريات', 'المتوسط', 'آخر طلب', 'أيام', 'الكباتن'];
        break;
        
    case 'meal':
        $report_title = 'تقرير الوجبات';
        $report_icon = 'bi-cup-straw';
        $report_data = getMealReport($conn, $start_date, $end_date, $entity_id);
        $summary_labels = [
            'meals_sold' => 'وجبات مباعة',
            'total_items_sold' => 'قطع مباعة',
            'total_revenue' => 'الإيرادات',
            'total_orders' => 'الطلبات',
            'avg_items_per_order' => 'متوسط القطع/طلب'
        ];
        $details_columns = ['الوجبة', 'التصنيف', 'السعر', 'الكمية', 'الإيرادات', 'الطلبات', 'النسبة', 'التصنيف ABC'];
        break;
        
    case 'category':
        $report_title = 'تقرير التصنيفات';
        $report_icon = 'bi-folder2-open';
        $report_data = getCategoryReport($conn, $start_date, $end_date, $entity_id);
        $summary_labels = [
            'active_categories' => 'تصنيفات نشطة',
            'meals_count' => 'وجبات',
            'total_items' => 'قطع مباعة',
            'total_revenue' => 'الإيرادات',
            'total_orders' => 'الطلبات'
        ];
        $details_columns = ['التصنيف', 'الوجبات', 'الكمية', 'الإيرادات', 'الطلبات', 'الحصة', 'أفضل وجبة'];
        break;
}

$page_title = $report_title;
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title><?php echo $page_title; ?> - ماكس بروست</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Tajawal', 'Segoe UI', sans-serif; background: #f0f2f5; overflow-x: hidden; }
        .main-content { margin-right: 280px; padding: 20px; transition: all 0.3s; min-height: 100vh; }
        
        .report-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px; padding: 20px 25px; margin-bottom: 25px; color: white;
            display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px;
            box-shadow: 0 10px 30px rgba(102,126,234,0.2);
        }
        .report-header h2 { font-size: 1.5rem; margin: 0; display: flex; align-items: center; gap: 10px; }
        .report-header .date-badge { background: rgba(255,255,255,0.2); padding: 8px 18px; border-radius: 30px; font-size: 0.85rem; backdrop-filter: blur(10px); }
        
        .report-tabs {
            display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 25px;
            background: white; padding: 12px 20px; border-radius: 50px; box-shadow: 0 2px 10px rgba(0,0,0,0.03);
        }
        .report-tab {
            padding: 8px 20px; border-radius: 30px; background: transparent; color: #4a5568;
            text-decoration: none; font-size: 0.85rem; font-weight: 500; transition: all 0.3s;
            display: inline-flex; align-items: center; gap: 8px;
        }
        .report-tab:hover { background: #f0f2f5; color: #667eea; }
        .report-tab.active { background: linear-gradient(135deg, #667eea, #764ba2); color: white; box-shadow: 0 4px 12px rgba(102,126,234,0.3); }
        
        .filter-card {
            background: white; border-radius: 20px; padding: 20px; margin-bottom: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.05);
        }
        .filter-title { font-size: 0.9rem; font-weight: 600; color: #1a2c3e; margin-bottom: 15px; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0; display: flex; align-items: center; gap: 8px; }
        .filter-group { margin-bottom: 15px; }
        .filter-group label { font-size: 0.75rem; font-weight: 600; color: #4a5568; margin-bottom: 5px; display: block; }
        .filter-group select, .filter-group input {
            width: 100%; padding: 10px 12px; border: 2px solid #e2e8f0; border-radius: 12px;
            font-size: 0.85rem; transition: all 0.2s; background: white;
        }
        .filter-group select:focus, .filter-group input:focus { border-color: #667eea; outline: none; box-shadow: 0 0 0 3px rgba(102,126,234,0.1); }
        .btn-primary-custom { background: linear-gradient(135deg, #667eea, #764ba2); color: white; border: none; border-radius: 12px; padding: 10px 20px; font-weight: 600; transition: all 0.3s; width: 100%; }
        .btn-primary-custom:hover { transform: translateY(-2px); box-shadow: 0 5px 20px rgba(102,126,234,0.4); }
        
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .stat-card {
            background: white; border-radius: 20px; padding: 20px; position: relative; overflow: hidden;
            transition: all 0.3s; border: 1px solid rgba(0,0,0,0.03); box-shadow: 0 5px 20px rgba(0,0,0,0.03);
        }
        .stat-card:hover { transform: translateY(-3px); box-shadow: 0 10px 30px rgba(0,0,0,0.08); }
        .stat-card::before { content: ''; position: absolute; top: 0; right: 0; width: 4px; height: 100%; background: linear-gradient(135deg, #667eea, #764ba2); border-radius: 4px; }
        .stat-icon { width: 50px; height: 50px; border-radius: 15px; background: linear-gradient(135deg, #667eea20, #764ba220); display: flex; align-items: center; justify-content: center; font-size: 1.6rem; color: #667eea; margin-bottom: 12px; }
        .stat-value { font-size: 1.8rem; font-weight: 800; color: #1a2c3e; line-height: 1.2; }
        .stat-label { font-size: 0.7rem; color: #6c757d; margin-top: 5px; text-transform: uppercase; letter-spacing: 0.5px; }
        
        .summary-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .summary-card { background: white; border-radius: 16px; padding: 15px; text-align: center; transition: all 0.3s; border: 1px solid rgba(0,0,0,0.03); box-shadow: 0 2px 10px rgba(0,0,0,0.03); }
        .summary-card:hover { transform: translateY(-2px); }
        .summary-value { font-size: 1.5rem; font-weight: 800; color: #667eea; }
        .summary-label { font-size: 0.7rem; color: #6c757d; margin-top: 5px; }
        
        .table-container { background: white; border-radius: 20px; padding: 20px; box-shadow: 0 5px 20px rgba(0,0,0,0.03); overflow-x: auto; margin-bottom: 20px; }
        .table-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px; }
        .table-title { font-size: 1rem; font-weight: 600; color: #1a2c3e; display: flex; align-items: center; gap: 8px; }
        .export-buttons { display: flex; gap: 8px; }
        .btn-export { padding: 8px 16px; border-radius: 10px; font-size: 0.8rem; font-weight: 500; border: none; cursor: pointer; transition: all 0.2s; display: inline-flex; align-items: center; gap: 5px; }
        .btn-pdf { background: #dc2626; color: white; }
        .btn-excel { background: #10b981; color: white; }
        .btn-print { background: #6c757d; color: white; }
        .btn-export:hover { transform: translateY(-2px); opacity: 0.9; }
        
        .report-table { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
        .report-table th { background: #f8fafc; padding: 12px 8px; font-weight: 600; color: #1a2c3e; border-bottom: 2px solid #e2e8f0; text-align: center; white-space: nowrap; }
        .report-table td { padding: 10px 8px; border-bottom: 1px solid #e9ecef; text-align: center; white-space: nowrap; }
        .report-table tr:hover { background: #f8fafc; }
        
        .badge-class { display: inline-block; padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 600; }
        .badge-A { background: #dcfce7; color: #166534; }
        .badge-B { background: #fef3c7; color: #92400e; }
        .badge-C { background: #fee2e2; color: #991b1b; }
        .badge-D { background: #e2e3e5; color: #383d41; }
        .badge-success { background: #10b98120; color: #10b981; }
        .badge-pending { background: #fff3cd; color: #856404; }
        .badge-accepted { background: #cce5ff; color: #004085; }
        .badge-on_the_way { background: #d1ecf1; color: #0c5460; }
        .badge-delivered { background: #d4edda; color: #155724; }
        
        .entity-link { color: #667eea; text-decoration: none; font-weight: 500; transition: all 0.2s; }
        .entity-link:hover { color: #764ba2; text-decoration: underline; }
        
        .empty-state { text-align: center; padding: 40px; color: #6c757d; }
        .empty-state i { font-size: 3rem; margin-bottom: 15px; opacity: 0.5; }
        
        @media (max-width: 768px) {
            .main-content { margin-right: 0; padding: 10px; }
            .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 10px; }
            .stat-value { font-size: 1.2rem; }
            .summary-grid { grid-template-columns: repeat(2, 1fr); }
            .report-tabs { border-radius: 20px; overflow-x: auto; flex-wrap: nowrap; }
            .report-tab { padding: 6px 15px; font-size: 0.75rem; white-space: nowrap; }
            .report-table th, .report-table td { padding: 8px 5px; font-size: 0.7rem; }
            .btn-export { padding: 6px 12px; font-size: 0.7rem; }
        }
        
        @media print {
            .no-print, .report-tabs, .filter-card, .export-buttons, .top-bar, .sidebar, #sidebar, .main-sidebar, aside, nav.sidebar, .navbar, .main-header, footer, .footer, button, .btn, .btn-export, .report-tab { display: none !important; visibility: hidden !important; }
            .main-content { margin: 0 !important; padding: 10px !important; width: 100% !important; position: relative !important; left: 0 !important; right: 0 !important; top: 0 !important; }
            body { background: white !important; margin: 0 !important; padding: 0 !important; }
            .report-table { width: 100% !important; font-size: 9pt !important; }
            .report-table th, .report-table td { border: 1px solid #ddd !important; padding: 4px !important; }
            .stat-card, .summary-card, .table-container, .report-header { break-inside: avoid; page-break-inside: avoid; }
            .stat-card, .summary-card, .table-container { background: white !important; border: 1px solid #ddd !important; box-shadow: none !important; }
            .report-header { background: none !important; color: black !important; border-bottom: 2px solid #667eea !important; box-shadow: none !important; }
            .report-header h2 { color: black !important; }
            .date-badge { background: #f0f0f0 !important; border: 1px solid #ddd !important; color: black !important; }
            .stat-value { color: #333 !important; }
            .summary-value { color: #28a745 !important; }
            .report-table th { background: #f0f0f0 !important; color: black !important; border: 1px solid #ddd !important; }
        }
    </style>
</head>
<body>

<div class="main-content">
    <!-- رأس التقرير -->
    <div class="report-header">
        <h2><i class="bi <?php echo $report_icon; ?>"></i> <?php echo $report_title; ?></h2>
        <div class="date-badge">
            <i class="bi bi-calendar3 me-1"></i>
            <?php echo date('Y-m-d', strtotime($start_date)); ?> - <?php echo date('Y-m-d', strtotime($end_date)); ?>
        </div>
    </div>
    
    <!-- أزرار اختيار نوع التقرير -->
    <div class="report-tabs no-print">
        <a href="?report_type=cashier&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $entity_id; ?>" class="report-tab <?php echo $report_type == 'cashier' ? 'active' : ''; ?>">
            <i class="bi bi-person-workspace"></i> كاشير
        </a>
        <a href="?report_type=captain&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $entity_id; ?>" class="report-tab <?php echo $report_type == 'captain' ? 'active' : ''; ?>">
            <i class="bi bi-truck"></i> كباتن
        </a>
        <a href="?report_type=customer&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $entity_id; ?>" class="report-tab <?php echo $report_type == 'customer' ? 'active' : ''; ?>">
            <i class="bi bi-people"></i> عملاء
        </a>
        <a href="?report_type=meal&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $entity_id; ?>" class="report-tab <?php echo $report_type == 'meal' ? 'active' : ''; ?>">
            <i class="bi bi-cup-straw"></i> وجبات
        </a>
        <a href="?report_type=category&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $entity_id; ?>" class="report-tab <?php echo $report_type == 'category' ? 'active' : ''; ?>">
            <i class="bi bi-folder2-open"></i> تصنيفات
        </a>
    </div>
    
    <!-- فلتر التقارير -->
    <div class="filter-card no-print">
        <div class="filter-title"><i class="bi bi-funnel"></i> فلترة التقرير</div>
        <form method="GET" id="reportForm">
            <input type="hidden" name="report_type" value="<?php echo $report_type; ?>">
            <div class="row g-3">
                <div class="col-md-3 col-sm-6">
                    <div class="filter-group">
                        <label><i class="bi bi-calendar-start"></i> من تاريخ</label>
                        <input type="date" name="start_date" value="<?php echo $start_date; ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="filter-group">
                        <label><i class="bi bi-calendar-end"></i> إلى تاريخ</label>
                        <input type="date" name="end_date" value="<?php echo $end_date; ?>" class="form-control">
                    </div>
                </div>
                <div class="col-md-3 col-sm-6">
                    <div class="filter-group">
                        <label><i class="bi bi-person"></i> اختر العنصر</label>
                        <select name="entity_id" class="form-select">
                            <option value="0">عرض الكل</option>
                            <?php
                            switch($report_type) {
                                case 'cashier':
                                    $cashiers->data_seek(0);
                                    while($row = $cashiers->fetch_assoc()) {
                                        $selected = ($entity_id == $row['id']) ? 'selected' : '';
                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>' . htmlspecialchars($row['name']) . ' - ' . htmlspecialchars($row['branch'] ?? 'رئيسي') . '</option>';
                                    }
                                    break;
                                case 'captain':
                                    $captains->data_seek(0);
                                    while($row = $captains->fetch_assoc()) {
                                        $selected = ($entity_id == $row['id']) ? 'selected' : '';
                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>' . htmlspecialchars($row['name']) . ' - ' . htmlspecialchars($row['phone']) . '</option>';
                                    }
                                    break;
                                case 'customer':
                                    $customers->data_seek(0);
                                    while($row = $customers->fetch_assoc()) {
                                        $selected = ($entity_id == $row['id']) ? 'selected' : '';
                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>' . htmlspecialchars($row['name']) . ' - ' . htmlspecialchars($row['phone']) . '</option>';
                                    }
                                    break;
                                case 'meal':
                                    $meals->data_seek(0);
                                    while($row = $meals->fetch_assoc()) {
                                        $selected = ($entity_id == $row['id']) ? 'selected' : '';
                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>' . htmlspecialchars($row['name']) . ' (' . htmlspecialchars($row['category'] ?? 'بدون') . ')</option>';
                                    }
                                    break;
                                case 'category':
                                    $categories->data_seek(0);
                                    while($row = $categories->fetch_assoc()) {
                                        $selected = ($entity_id == $row['id']) ? 'selected' : '';
                                        echo '<option value="' . $row['id'] . '" ' . $selected . '>' . htmlspecialchars($row['name']) . '</option>';
                                    }
                                    break;
                            }
                            ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3 col-sm-6 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary-custom"><i class="bi bi-search"></i> عرض التقرير</button>
                </div>
            </div>
        </form>
    </div>
    
    <!-- بطاقات الإحصائيات العامة -->
    <div class="stats-grid">
        <div class="stat-card"><div class="stat-icon"><i class="bi bi-cart"></i></div><div class="stat-value"><?php echo number_format($global_stats['total_orders']); ?></div><div class="stat-label">إجمالي الطلبات</div></div>
        <div class="stat-card"><div class="stat-icon"><i class="bi bi-cash-stack"></i></div><div class="stat-value"><?php echo number_format($global_stats['total_revenue']); ?></div><div class="stat-label">إجمالي الإيرادات (ريال)</div></div>
        <div class="stat-card"><div class="stat-icon"><i class="bi bi-graph-up"></i></div><div class="stat-value"><?php echo number_format($global_stats['avg_order']); ?></div><div class="stat-label">متوسط الطلب (ريال)</div></div>
        <div class="stat-card"><div class="stat-icon"><i class="bi bi-people"></i></div><div class="stat-value"><?php echo number_format($global_stats['unique_customers']); ?></div><div class="stat-label">عملاء فريدين</div></div>
    </div>
    
    <!-- بطاقات الملخص الخاص بالتقرير -->
    <?php if (isset($report_data['summary']) && $report_data['summary']): ?>
    <div class="summary-grid">
        <?php foreach($report_data['summary'] as $key => $value): ?>
            <?php if (isset($summary_labels[$key]) && $value > 0): ?>
            <div class="summary-card">
                <div class="summary-value">
                    <?php 
                    if (strpos($key, 'revenue') !== false || strpos($key, 'spent') !== false) {
                        echo number_format($value, 0) . '<small style="font-size:0.6rem"> ريال</small>';
                    } elseif (strpos($key, 'time') !== false) {
                        echo number_format($value) . '<small style="font-size:0.6rem"> د</small>';
                    } else {
                        echo number_format($value);
                    }
                    ?>
                </div>
                <div class="summary-label"><?php echo $summary_labels[$key]; ?></div>
            </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    
    <!-- جدول البيانات الرئيسي -->
    <div class="table-container">
        <div class="table-header no-print">
            <div class="table-title"><i class="bi bi-table"></i> تفاصيل <?php echo $report_title; ?></div>
            <div class="export-buttons">
                <button type="button" class="btn-export btn-pdf" id="pdfExportBtn">
                    <i class="bi bi-file-pdf"></i> تحميل PDF
                </button>
                <button type="button" class="btn-export btn-excel" id="excelExportBtn">
                    <i class="bi bi-file-excel"></i> تحميل Excel
                </button>
                <button type="button" class="btn-export btn-print" id="printBtn">
                    <i class="bi bi-printer"></i> طباعة
                </button>
            </div>
        </div>
        
        <table class="report-table" id="reportTable">
            <thead>
                <tr><?php foreach($details_columns as $col): ?><th><?php echo $col; ?></th><?php endforeach; ?></thead>
            <tbody>
                <?php if (isset($report_data['details']) && $report_data['details'] && $report_data['details']->num_rows > 0): ?>
                    <?php while($row = $report_data['details']->fetch_assoc()): ?>
                     <tr>
                        <?php switch($report_type):
                            case 'cashier': ?>
                                 <td><a href="?report_type=cashier&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $row['id']; ?>" class="entity-link"><?php echo htmlspecialchars($row['name']); ?> <i class="bi bi-box-arrow-up-right small"></i></a></td>
                                  <td><?php echo htmlspecialchars($row['branch'] ?: 'رئيسي'); ?></td>
                                  <td><?php echo number_format($row['orders_count']); ?></td>
                                  <td><?php echo number_format($row['total_revenue']); ?> ريال</td>
                                  <td><?php echo number_format($row['avg_order']); ?> ريال</td>
                                  <td><span class="badge-class badge-success"><?php echo number_format($row['completed']); ?></span></td>
                                  <td><?php echo number_format($row['cash_amount']); ?> ريال</td>
                                  <td><?php echo number_format($row['card_amount']); ?> ريال</td>
                                  <td><?php echo number_format($row['customers_served']); ?></td>
                            <?php break;
                            case 'captain': ?>
                                  <td><a href="?report_type=captain&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $row['id']; ?>" class="entity-link"><?php echo htmlspecialchars($row['name']); ?> <i class="bi bi-box-arrow-up-right small"></i></a></td>
                                  <td><?php echo htmlspecialchars($row['phone']); ?></td>
                                  <td><?php echo htmlspecialchars($row['vehicle_info'] ?: '-'); ?></td>
                                  <td><?php echo number_format($row['deliveries_count']); ?></td>
                                  <td><?php echo number_format($row['total_revenue']); ?> ريال</td>
                                  <td><?php echo number_format($row['avg_order']); ?> ريال</td>
                                  <td><span class="badge-class badge-success"><?php echo number_format($row['completed']); ?></span></td>
                                  <td><?php echo number_format($row['working_days']); ?> يوم</td>
                                  <td><?php echo number_format($row['customers_served']); ?></td>
                            <?php break;
                            case 'customer': ?>
                                  <td><a href="?report_type=customer&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $row['id']; ?>" class="entity-link"><?php echo htmlspecialchars($row['name']); ?> <i class="bi bi-box-arrow-up-right small"></i></a></td>
                                  <td><?php echo htmlspecialchars($row['phone']); ?></td>
                                  <td><?php echo number_format($row['orders_count']); ?></td>
                                  <td><?php echo number_format($row['total_spent']); ?> ريال</td>
                                  <td><?php echo number_format($row['avg_order']); ?> ريال</td>
                                  <td><?php echo date('Y-m-d', strtotime($row['last_order_date'])); ?></td>
                                  <td><?php echo number_format($row['days_since_last']); ?> يوم</td>
                                  <td><?php echo number_format($row['captains_used']); ?></td>
                            <?php break;
                            case 'meal': ?>
                                  <td><a href="?report_type=meal&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $row['id']; ?>" class="entity-link"><?php echo htmlspecialchars($row['name']); ?> <i class="bi bi-box-arrow-up-right small"></i></a></td>
                                  <td><?php echo htmlspecialchars($row['category']); ?></td>
                                  <td><?php echo number_format($row['unit_price']); ?> ريال</td>
                                  <td><?php echo number_format($row['quantity_sold']); ?></td>
                                  <td><?php echo number_format($row['total_revenue']); ?> ريال</td>
                                  <td><?php echo number_format($row['orders_count']); ?></td>
                                  <td><?php echo $row['revenue_percent']; ?>%</td>
                                  <td><span class="badge-class badge-<?php echo $row['abc_class']; ?>"><?php echo $row['abc_class']; ?></span></td>
                            <?php break;
                            case 'category': ?>
                                  <td><a href="?report_type=category&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&entity_id=<?php echo $row['id']; ?>" class="entity-link"><?php echo htmlspecialchars($row['name']); ?> <i class="bi bi-box-arrow-up-right small"></i></a></td>
                                  <td><?php echo number_format($row['meals_count']); ?></td>
                                  <td><?php echo number_format($row['quantity_sold']); ?></td>
                                  <td><?php echo number_format($row['total_revenue']); ?> ريال</td>
                                  <td><?php echo number_format($row['orders_count']); ?></td>
                                  <td><?php echo $row['revenue_share']; ?>%</td>
                                  <td><?php echo htmlspecialchars($row['top_meal'] ?: '-'); ?></td>
                            <?php break;
                        endswitch; ?>
                      </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                      <tr><td colspan="<?php echo count($details_columns); ?>" class="empty-state"><i class="bi bi-inbox"></i><p>لا توجد بيانات للفترة المحددة</p></td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- تفاصيل الطلبات للكاشير -->
    <?php if ($report_type == 'cashier' && $entity_id > 0): 
        $orders_details = $conn->query("
            SELECT o.id, DATE(o.created_at) as order_date, o.created_at, c.name as customer_name, c.phone as customer_phone,
                   o.total, o.status, o.payment_method, cp.name as captain_name,
                   COUNT(oi.id) as items_count, GROUP_CONCAT(DISTINCT m.name SEPARATOR ', ') as items_list, o.notes
            FROM orders o
            JOIN customers c ON o.customer_id = c.id
            LEFT JOIN captains cp ON o.captain_id = cp.id
            LEFT JOIN order_items oi ON o.id = oi.order_id
            LEFT JOIN meals m ON oi.meal_id = m.id
            WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date' AND o.cashier_id = $entity_id
            GROUP BY o.id ORDER BY o.created_at DESC
        ");
    ?>
    <div class="table-container">
        <div class="table-header">
            <div class="table-title"><i class="bi bi-receipt"></i> تفاصيل الطلبات - <?php echo htmlspecialchars($cashier_name); ?></div>
        </div>
        <div style="overflow-x: auto;">
            <table class="report-table">
                <thead> <tr><th>#</th><th>التاريخ</th><th>العميل</th><th>الهاتف</th><th>المبلغ</th><th>الحالة</th><th>طريقة الدفع</th><th>الكابتن</th><th>الأصناف</th><th>الوجبات</th> </tr></thead>
                <tbody>
                    <?php 
                    $status_text = ['pending' => 'معلق', 'accepted' => 'مقبول', 'on_the_way' => 'في الطريق', 'delivered' => 'مكتمل'];
                    if ($orders_details && $orders_details->num_rows > 0):
                        while($order = $orders_details->fetch_assoc()): 
                    ?>
                      <tr>
                        <td>#<?php echo $order['id']; ?></td>
                        <td><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                        <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                        <td><?php echo htmlspecialchars($order['customer_phone']); ?></td>
                        <td><?php echo number_format($order['total'], 2); ?> ريال</td>
                        <td><span class="badge-class badge-<?php echo $order['status']; ?>"><?php echo $status_text[$order['status']]; ?></span></td>
                        <td><?php echo $order['payment_method'] == 'cash' ? 'نقدي' : 'بطاقة'; ?></td>
                        <td><?php echo htmlspecialchars($order['captain_name'] ?: 'غير معين'); ?></td>
                        <td><?php echo $order['items_count']; ?></td>
                        <td style="max-width: 250px; white-space: normal;"><?php echo htmlspecialchars($order['items_list'] ?: '-'); ?></td>
                      </tr>
                    <?php endwhile; else: ?>
                      <tr><td colspan="10" class="empty-state"><i class="bi bi-inbox"></i><p>لا توجد طلبات</p></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- تفاصيل الطلبات للكابتن -->
    <?php if ($report_type == 'captain' && $entity_id > 0): 
        $captain_orders = $conn->query("
            SELECT o.id, DATE(o.created_at) as order_date, o.created_at, c.name as customer_name, c.phone as customer_phone,
                   c.address as customer_address, o.total, o.status, o.payment_method, cash.name as cashier_name,
                   COUNT(oi.id) as items_count, o.notes
            FROM orders o
            JOIN customers c ON o.customer_id = c.id
            LEFT JOIN cashiers cash ON o.cashier_id = cash.id
            LEFT JOIN order_items oi ON o.id = oi.order_id
            WHERE DATE(o.created_at) BETWEEN '$start_date' AND '$end_date' AND o.captain_id = $entity_id
            GROUP BY o.id ORDER BY o.created_at DESC
        ");
    ?>
    <div class="table-container">
        <div class="table-header">
            <div class="table-title"><i class="bi bi-truck"></i> تفاصيل التوصيلات - <?php echo htmlspecialchars($captain_name); ?></div>
        </div>
        <div style="overflow-x: auto;">
            <table class="report-table">
                <thead> <tr><th>#</th><th>التاريخ</th><th>العميل</th><th>الهاتف</th><th>العنوان</th><th>المبلغ</th><th>الحالة</th><th>طريقة الدفع</th><th>الكاشير</th><th>الأصناف</th> </tr></thead>
                <tbody>
                    <?php 
                    $status_text = ['pending' => 'معلق', 'accepted' => 'مقبول', 'on_the_way' => 'في الطريق', 'delivered' => 'مكتمل'];
                    if ($captain_orders && $captain_orders->num_rows > 0):
                        while($order = $captain_orders->fetch_assoc()): 
                    ?>
                      <tr>
                        <td>#<?php echo $order['id']; ?></td>
                        <td><?php echo date('Y-m-d H:i', strtotime($order['created_at'])); ?></td>
                        <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                        <td><?php echo htmlspecialchars($order['customer_phone']); ?></td>
                        <td style="max-width: 200px; white-space: normal;"><?php echo htmlspecialchars($order['customer_address'] ?: '-'); ?></td>
                        <td><?php echo number_format($order['total'], 2); ?> ريال</td>
                        <td><span class="badge-class badge-<?php echo $order['status']; ?>"><?php echo $status_text[$order['status']]; ?></span></td>
                        <td><?php echo $order['payment_method'] == 'cash' ? 'نقدي' : 'بطاقة'; ?></td>
                        <td><?php echo htmlspecialchars($order['cashier_name'] ?: 'غير معين'); ?></td>
                        <td><?php echo $order['items_count']; ?></td>
                      </tr>
                    <?php endwhile; else: ?>
                      <tr><td colspan="10" class="empty-state"><i class="bi bi-inbox"></i><p>لا توجد توصيلات</p></td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<script>
// دالة التحميل المباشر
function downloadReport(format) {
    const reportType = '<?php echo $report_type; ?>';
    const startDate = '<?php echo $start_date; ?>';
    const endDate = '<?php echo $end_date; ?>';
    const entityId = '<?php echo $entity_id; ?>';
    
    let url = `reports_download.php?type=${reportType}&format=${format}&start_date=${startDate}&end_date=${endDate}`;
    if (entityId && entityId != 0) {
        url += `&entity_id=${entityId}`;
    }
    
    // إنشاء رابط مؤقت للتحميل المباشر
    const link = document.createElement('a');
    link.href = url;
    link.download = `${reportType}_report_${startDate}_to_${endDate}.${format === 'pdf' ? 'pdf' : 'csv'}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    return false;
}

// تهيئة الأزرار عند تحميل الصفحة
document.addEventListener('DOMContentLoaded', function() {
    // زر PDF
    const pdfBtn = document.getElementById('pdfExportBtn');
    if (pdfBtn) {
        pdfBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            downloadReport('pdf');
            return false;
        };
    }
    
    // زر Excel
    const excelBtn = document.getElementById('excelExportBtn');
    if (excelBtn) {
        excelBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            downloadReport('excel');
            return false;
        };
    }
    
    // زر الطباعة
    const printBtn = document.getElementById('printBtn');
    if (printBtn) {
        printBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            window.print();
            return false;
        };
    }
    
    console.log('Reports page ready - Direct download enabled');
});
</script>

<?php include 'includes/footer.php'; ?>