<?php
/**
 * captain_daily_report.php - تقرير يومي للكابتن
 */

require_once 'config.php';
checkCashierAuth();

$captain_id = isset($_GET['captain_id']) ? (int)$_GET['captain_id'] : 0;
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

if (!$captain_id) {
    header('Location: cashier_dashboard.php');
    exit();
}

// جلب معلومات الكابتن
$captain = $conn->query("SELECT * FROM captains WHERE id = $captain_id")->fetch_assoc();

if (!$captain) {
    header('Location: cashier_dashboard.php');
    exit();
}

// جلب تقرير اليوم
$report = $conn->query("
    SELECT 
        COUNT(*) as total_orders,
        COUNT(CASE WHEN status = 'delivered' THEN 1 END) as completed_orders,
        COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_orders,
        COALESCE(SUM(total), 0) as total_revenue,
        MIN(created_at) as first_order,
        MAX(created_at) as last_order
    FROM orders
    WHERE captain_id = $captain_id 
    AND DATE(created_at) = '$date'
")->fetch_assoc();

// جلب تفاصيل الطلبات
$orders = $conn->query("
    SELECT o.*, c.name as customer_name, c.phone as customer_phone, c.address
    FROM orders o
    JOIN customers c ON o.customer_id = c.id
    WHERE o.captain_id = $captain_id 
    AND DATE(o.created_at) = '$date'
    ORDER BY o.created_at DESC
");

$orders_list = [];
while ($row = $orders->fetch_assoc()) {
    $orders_list[] = $row;
}

// حساب ساعات العمل
$hours_worked = 0;
if ($report['first_order'] && $report['last_order']) {
    $start = new DateTime($report['first_order']);
    $end = new DateTime($report['last_order']);
    $interval = $start->diff($end);
    $hours_worked = $interval->h + ($interval->days * 24);
}

$page_title = 'تقرير الكابتن - ' . $captain['name'];
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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 href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        body {
            font-family: 'Cairo', sans-serif;
            background: #f8f9fa;
            padding: 20px;
        }
        
        .report-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 20px;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 1.5rem;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
            height: 100%;
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            margin-bottom: 1rem;
        }
        
        .stat-icon.orders { background: #e3f2fd; color: #1976d2; }
        .stat-icon.completed { background: #e8f5e9; color: #388e3c; }
        .stat-icon.revenue { background: #fff3e0; color: #f57c00; }
        .stat-icon.hours { background: #f3e5f5; color: #7b1fa2; }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 0.3rem;
        }
        
        .stat-label {
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .table-custom {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 20px rgba(0,0,0,0.05);
        }
        
        .table-custom thead {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-print {
            background: white;
            color: #667eea;
            border: none;
            padding: 0.8rem 2rem;
            border-radius: 50px;
            font-weight: 600;
            transition: all 0.3s;
        }
        
        .btn-print:hover {
            background: #f8f9fa;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background: white;
                padding: 0;
            }
            .report-header {
                background: #667eea !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .table-custom thead {
                background: #667eea !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- زر الطباعة -->
        <div class="text-start mb-3 no-print">
            <button onclick="window.print()" class="btn-print">
                <i class="bi bi-printer"></i> طباعة التقرير
            </button>
            <a href="cashier_dashboard.php" class="btn btn-secondary ms-2">
                <i class="bi bi-arrow-right"></i> عودة
            </a>
        </div>
        
        <!-- رأس التقرير -->
        <div class="report-header">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h2 class="mb-2">
                        <i class="bi bi-person-badge"></i> تقرير الكابتن
                    </h2>
                    <h3 class="mb-0"><?php echo htmlspecialchars($captain['name']); ?></h3>
                    <p class="mb-0">
                        <i class="bi bi-telephone"></i> <?php echo $captain['phone']; ?>
                        <?php if ($captain['vehicle_info']): ?>
                            | <i class="bi bi-truck"></i> <?php echo $captain['vehicle_info']; ?>
                        <?php endif; ?>
                    </p>
                </div>
                <div class="col-md-4 text-md-start text-center">
                    <h4 class="mb-0">
                        <i class="bi bi-calendar"></i> 
                        <?php echo date('Y-m-d', strtotime($date)); ?>
                    </h4>
                    <p class="mb-0">تقرير يومي</p>
                </div>
            </div>
        </div>
        
        <!-- الإحصائيات -->
        <div class="row g-4 mb-4">
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <div class="stat-icon orders">
                        <i class="bi bi-receipt"></i>
                    </div>
                    <div class="stat-number"><?php echo $report['total_orders']; ?></div>
                    <div class="stat-label">إجمالي الطلبات</div>
                </div>
            </div>
            
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <div class="stat-icon completed">
                        <i class="bi bi-check-circle"></i>
                    </div>
                    <div class="stat-number"><?php echo $report['completed_orders']; ?></div>
                    <div class="stat-label">الطلبات المكتملة</div>
                </div>
            </div>
            
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <div class="stat-icon revenue">
                        <i class="bi bi-currency-exchange"></i>
                    </div>
                    <div class="stat-number"><?php echo number_format($report['total_revenue'], 2); ?></div>
                    <div class="stat-label">إجمالي الإيرادات</div>
                </div>
            </div>
            
            <div class="col-md-3 col-6">
                <div class="stat-card">
                    <div class="stat-icon hours">
                        <i class="bi bi-clock-history"></i>
                    </div>
                    <div class="stat-number"><?php echo $hours_worked; ?></div>
                    <div class="stat-label">ساعات العمل</div>
                </div>
            </div>
        </div>
        
        <!-- تفاصيل الطلبات -->
        <div class="table-responsive table-custom">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>العميل</th>
                        <th>الهاتف</th>
                        <th>العنوان</th>
                        <th>المبلغ</th>
                        <th>الحالة</th>
                        <th>الوقت</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders_list)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4">
                            <i class="bi bi-inbox" style="font-size: 2rem;"></i>
                            <h5 class="mt-2">لا توجد طلبات في هذا اليوم</h5>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($orders_list as $order): ?>
                        <tr>
                            <td>#<?php echo $order['id']; ?></td>
                            <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                            <td><?php echo $order['customer_phone']; ?></td>
                            <td><?php echo htmlspecialchars($order['address'] ?: 'لا يوجد'); ?></td>
                            <td class="fw-bold"><?php echo number_format($order['total'], 2); ?> ريال</td>
                            <td>
                                <span class="badge bg-<?php echo getStatusBadge($order['status']); ?>">
                                    <?php echo getStatusText($order['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('H:i', strtotime($order['created_at'])); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- ملخص -->
        <div class="row mt-4">
            <div class="col-md-6">
                <div class="stat-card">
                    <h5 class="mb-3">ملخص الأداء</h5>
                    <table class="table table-sm">
                        <tr>
                            <td>نسبة الإنجاز:</td>
                            <td class="fw-bold">
                                <?php 
                                $completion_rate = $report['total_orders'] > 0 
                                    ? round(($report['completed_orders'] / $report['total_orders']) * 100, 2) 
                                    : 0;
                                echo $completion_rate . '%';
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td>متوسط قيمة الطلب:</td>
                            <td class="fw-bold">
                                <?php 
                                $avg_order = $report['completed_orders'] > 0 
                                    ? $report['total_revenue'] / $report['completed_orders'] 
                                    : 0;
                                echo number_format($avg_order, 2) . ' ريال';
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td>أول طلب:</td>
                            <td class="fw-bold">
                                <?php echo $report['first_order'] ? date('H:i', strtotime($report['first_order'])) : '-'; ?>
                            </td>
                        </tr>
                        <tr>
                            <td>آخر طلب:</td>
                            <td class="fw-bold">
                                <?php echo $report['last_order'] ? date('H:i', strtotime($report['last_order'])) : '-'; ?>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    // طباعة التقرير
    window.onbeforeprint = function() {
        // إخفاء الأزرار قبل الطباعة
        document.querySelectorAll('.no-print').forEach(el => el.style.display = 'none');
    };
    
    window.onafterprint = function() {
        // إظهار الأزرار بعد الطباعة
        document.querySelectorAll('.no-print').forEach(el => el.style.display = 'block');
    };
    </script>
</body>
</html>