<?php
include 'config.php';
checkCaptainAuth();

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');

$captain_id = $_SESSION['captain_id'];
$t = isset($_GET['t']) ? (int)$_GET['t'] : 0;

// Get current orders count
$count_result = $conn->query("SELECT COUNT(*) as c FROM orders WHERE captain_id='$captain_id' AND status!='delivered'");
$current_count = $count_result->fetch_assoc()['c'];

// Get new orders count (since last check - simple)
$last_check = date('Y-m-d H:i:s', time() - 30);
$new_result = $conn->query("SELECT COUNT(*) as c FROM orders WHERE captain_id='$captain_id' AND status='pending' AND created_at>'$last_check'");
$new_count = $new_result->fetch_assoc()['c'];

// Get orders HTML
$orders = $conn->query("
    SELECT o.id, o.total, o.status, o.created_at,
           c.name as customer_name, c.phone as customer_phone, 
           c.address as customer_address, c.latitude, c.longitude
    FROM orders o FORCE INDEX (idx_captain_status)
    JOIN customers c ON o.customer_id = c.id 
    WHERE o.captain_id = '$captain_id' AND o.status != 'delivered'
    ORDER BY o.created_at DESC
    LIMIT 50
");

ob_start();
if($orders->num_rows > 0){
    while($o=$orders->fetch_assoc()){
        $coords = !empty($o['latitude']) && !empty($o['longitude']);
        $gmaps = $coords ? "https://www.google.com/maps/dir/?api=1&destination={$o['latitude']},{$o['longitude']}" : "https://www.google.com/maps/search/?api=1&query=".urlencode($o['customer_address']);
        $status_text = $o['status']=='pending' ? 'جديد' : ($o['status']=='accepted' ? 'مقبول' : 'توصيل');
        $status_icon = $o['status']=='pending' ? 'hourglass-split' : ($o['status']=='accepted' ? 'check-circle' : 'truck');
        ?>
        <div class="order-card" data-id="<?php echo $o['id']; ?>">
            <div class="order-header">
                <span class="order-id">#<?php echo $o['id']; ?></span>
                <span class="badge <?php echo $o['status']; ?>"><i class="bi bi-<?php echo $status_icon; ?>"></i> <?php echo $status_text; ?></span>
            </div>
            <div class="info-row"><i class="bi bi-person"></i><span><?php echo htmlspecialchars($o['customer_name']); ?></span></div>
            <div class="info-row"><i class="bi bi-telephone"></i><a href="tel:<?php echo $o['customer_phone']; ?>" class="text-dark text-decoration-none"><?php echo $o['customer_phone']; ?></a></div>
            <div class="info-row"><i class="bi bi-geo-alt"></i><span class="small"><?php echo mb_substr($o['customer_address'],0,40); ?></span></div>
            <?php if($coords): ?>
            <div class="coords"><i class="bi bi-pin-map text-primary"></i> <?php echo number_format($o['latitude'],5); ?>, <?php echo number_format($o['longitude'],5); ?><button class="btn btn-sm p-0 ms-2" onclick="copyCoords(<?php echo $o['latitude']; ?>,<?php echo $o['longitude']; ?>)"><i class="bi bi-clipboard"></i></button></div>
            <?php endif; ?>
            <div class="total"><i class="bi bi-currency-dollar"></i> <?php echo number_format($o['total'],2); ?> ريال</div>
            <div class="actions">
                <?php if($o['status']=='pending'): ?>
                <button class="btn-sm btn-success" onclick="confirmAction(<?php echo $o['id']; ?>,'accept',this)"><i class="bi bi-check-circle"></i> قبول</button>
                <?php elseif($o['status']=='accepted'): ?>
                <button class="btn-sm btn-primary" onclick="confirmAction(<?php echo $o['id']; ?>,'deliver',this)"><i class="bi bi-truck"></i> توصيل</button>
                <?php elseif($o['status']=='on_the_way'): ?>
                <button class="btn-sm btn-success" onclick="confirmAction(<?php echo $o['id']; ?>,'complete',this)"><i class="bi bi-check2-circle"></i> تسليم</button>
                <?php endif; ?>
                <a href="order_details.php?id=<?php echo $o['id']; ?>" class="btn-sm btn-info"><i class="bi bi-list"></i> تفاصيل</a>
                <a href="<?php echo $gmaps; ?>" target="_blank" class="btn-sm btn-google"><i class="bi bi-google"></i> خرائط</a>
            </div>
        </div>
        <?php
    }
} else {
    echo '<div class="empty"><i class="bi bi-inbox" style="font-size:2.5rem;color:#d1d5db;"></i><p class="mt-2 text-muted">لا توجد طلبات</p></div>';
}
$html = ob_get_clean();

echo json_encode([
    'success' => true,
    'new_orders' => $new_count,
    'current' => $current_count,
    'html' => $html,
    'time' => time()
]);
?>