<?php
/**
 * Captain Settlements Page
 */

require_once 'config.php';
checkCashierAuth();

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

// الحصول على جميع الكباتن للفلتر
$captains = $conn->query("SELECT id, name, phone FROM captains ORDER BY name");

// الحصول على ملخص الكابتن إذا تم اختياره
$captain_summary = null;
$captain_orders = null;

if ($captain_id > 0) {
    // الملخص
    $summary_sql = "
        SELECT 
            COUNT(*) as total_orders,
            SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
            SUM(CASE WHEN status = 'delivered' THEN total ELSE 0 END) as total_collected,
            AVG(CASE WHEN status = 'delivered' THEN total ELSE NULL END) as avg_order,
            COUNT(DISTINCT DATE(created_at)) as working_days
        FROM orders 
        WHERE captain_id = $captain_id
        AND DATE(created_at) BETWEEN '$start_date' AND '$end_date'";
    
    $captain_summary = $conn->query($summary_sql)->fetch_assoc();
    
    // قائمة الطلبات
    $orders_sql = "
        SELECT o.*, c.name as customer_name
        FROM orders o
        JOIN customers c ON o.customer_id = c.id
        WHERE o.captain_id = $captain_id
        AND DATE(o.created_at) BETWEEN '$start_date' AND '$end_date'
        ORDER BY o.created_at DESC";
    
    $captain_orders = $conn->query($orders_sql);
}

$page_title = 'تسوية الكباتن';
?>
<!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=Tajawal:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <div class="cashier-app">
        <div class="container-fluid px-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4>
                    <i class="bi bi-cash-stack text-success me-2"></i>
                    تسوية الكباتن
                </h4>
                <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-arrow-right"></i>
                    العودة للرئيسية
                </a>
            </div>

            <!-- نموذج الفلتر -->
            <div class="report-header">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">اختر الكابتن</label>
                        <select name="captain_id" class="form-select" required>
                            <option value="">-- اختر الكابتن --</option>
                            <?php while ($cap = $captains->fetch_assoc()): ?>
                            <option value="<?php echo $cap['id']; ?>" <?php echo $captain_id == $cap['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cap['name']); ?> - <?php echo $cap['phone']; ?>
                            </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">من تاريخ</label>
                        <input type="date" name="start_date" class="form-control" value="<?php echo $start_date; ?>">
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">إلى تاريخ</label>
                        <input type="date" name="end_date" class="form-control" value="<?php echo $end_date; ?>">
                    </div>
                    
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i> عرض
                        </button>
                    </div>
                </form>
            </div>

            <?php if ($captain_id > 0 && $captain_summary): ?>
            <!-- ملخص الكابتن -->
            <div class="report-stats">
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $captain_summary['total_orders']; ?></div>
                    <div class="report-stat-label">إجمالي الطلبات</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $captain_summary['delivered_orders']; ?></div>
                    <div class="report-stat-label">الطلبات المكتملة</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo formatMoney($captain_summary['total_collected']); ?></div>
                    <div class="report-stat-label">إجمالي المحصل</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo formatMoney($captain_summary['avg_order']); ?></div>
                    <div class="report-stat-label">متوسط الطلب</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $captain_summary['working_days']; ?></div>
                    <div class="report-stat-label">أيام العمل</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value">
                        <?php 
                        $avg_daily = $captain_summary['working_days'] > 0 
                            ? $captain_summary['total_collected'] / $captain_summary['working_days']
                            : 0;
                        echo formatMoney($avg_daily);
                        ?>
                    </div>
                    <div class="report-stat-label">متوسط يومي</div>
                </div>
            </div>

            <!-- قائمة الطلبات -->
            <div class="report-table-container">
                <h5 class="mb-3">تفاصيل الطلبات</h5>
                <table class="report-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>التاريخ</th>
                            <th>العميل</th>
                            <th>المبلغ</th>
                            <th>الحالة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($captain_orders && $captain_orders->num_rows > 0): ?>
                            <?php $i = 1; 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 formatMoney($order['total']); ?></td>
                                <td>
                                    <span class="order-status <?php echo getStatusBadge($order['status']); ?>">
                                        <?php echo getStatusText($order['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="5" class="text-center py-4">لا توجد طلبات للكابتن في هذه الفترة</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-end"><strong>الإجمالي:</strong></td>
                            <td colspan="2"><strong><?php echo formatMoney($captain_summary['total_collected']); ?></strong></td>
                        </tr>
                    </tfoot>
                </table>
                
                <!-- أزرار الإجراءات -->
                <div class="d-flex gap-2 justify-content-end mt-4 no-print">
                    <button class="btn btn-success" onclick="printSettlement()">
                        <i class="bi bi-printer me-1"></i>طباعة كشف التسوية
                    </button>
                    <button class="btn btn-primary" onclick="markAsSettled()">
                        <i class="bi bi-check-circle me-1"></i>تسوية المبلغ
                    </button>
                </div>
            </div>
            <?php elseif ($captain_id > 0): ?>
            <div class="alert alert-warning">
                لا توجد بيانات للكابتن في هذه الفترة
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
    function printSettlement() {
        window.print();
    }

    function markAsSettled() {
        if (confirm('هل أنت متأكد من تسوية المبلغ مع الكابتن؟')) {
            // هنا يمكن إضافة منطق تسوية المبلغ في قاعدة البيانات
            alert('تم تسوية المبلغ بنجاح');
        }
    }
    </script>
</body>
</html>