<?php 
include 'header.php'; 
require_once __DIR__ . '/../db/config.php';

$driver_id = $_SESSION['driver_id'];
$pdo = db();

$stmt = $pdo->prepare(
    'SELECT ' .
    'o.id as order_id, ' .
    'o.status as order_status, ' .
    'o.delivery_address, ' .
    'u.name as customer_name, ' .
    'r.name as restaurant_name, ' .
    'r.address as restaurant_address ' .
    'FROM orders o ' .
    'JOIN driver_assignments da ON o.id = da.order_id ' .
    'JOIN users u ON o.user_id = u.id ' .
    'JOIN restaurants r ON o.restaurant_id = r.id ' .
    'WHERE da.driver_id = ? ' .
    'ORDER BY o.created_at DESC'
);
$stmt->execute([$driver_id]);
$assigned_orders = $stmt->fetchAll();

// Get available orders
$available_stmt = $pdo->prepare(
    'SELECT ' .
    'o.id as order_id, ' .
    'o.delivery_address, ' .
    'r.name as restaurant_name, ' .
    'r.address as restaurant_address ' .
    'FROM orders o ' .
    'JOIN restaurants r ON o.restaurant_id = r.id ' .
    'WHERE o.status = "ready for pickup" AND o.driver_id IS NULL ' .
    'ORDER BY o.created_at ASC'
);
$available_stmt->execute();
$available_orders = $available_stmt->fetchAll();


$order_statuses = ['out for delivery', 'picked up', 'delivered'];

?>

<main class="container">
    
    <div class="available-jobs">
        <h2>Available Jobs</h2>
        <?php if (empty($available_orders)): ?>
            <p>No jobs available at the moment.</p>
        <?php else: ?>
            <div class="order-list">
                <?php foreach ($available_orders as $order): ?>
                    <div class="order-card">
                        <h3>Order #<?php echo htmlspecialchars($order['order_id']); ?></h3>
                        <p><strong>Restaurant:</strong> <?php echo htmlspecialchars($order['restaurant_name']); ?></p>
                        <p><strong>Restaurant Address:</strong> <?php echo htmlspecialchars($order['restaurant_address']); ?></p>
                        <p><strong>Delivery Address:</strong> <?php echo htmlspecialchars($order['delivery_address']); ?></p>
                        <form action="accept_job.php" method="POST">
                            <input type="hidden" name="order_id" value="<?php echo $order['order_id']; ?>">
                            <button type="submit" class="btn-submit">Accept Job</button>
                        </form>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <hr>

    <h1>My Assigned Deliveries</h1>

    <?php if (isset($_GET['success'])): ?>
        <p class="success-message"><?php echo htmlspecialchars($_GET['success']); ?></p>
    <?php endif; ?>
    <?php if (isset($_GET['error'])): ?>
        <p class="error-message"><?php echo htmlspecialchars($_GET['error']); ?></p>
    <?php endif; ?>

    <div class="order-list">
        <?php if (empty($assigned_orders)): ?>
            <p>You have no assigned orders at the moment.</p>
        <?php else: ?>
            <?php foreach ($assigned_orders as $order): ?>
                <div class="order-card">
                    <h3>Order #<?php echo htmlspecialchars($order['order_id']); ?></h3>
                    <p><strong>Status:</strong> <?php echo htmlspecialchars(ucwords($order['order_status'])); ?></p>
                    <hr>
                    <p><strong>Customer:</strong> <?php echo htmlspecialchars($order['customer_name']); ?></p>
                    <p><strong>Delivery Address:</strong> <?php echo htmlspecialchars($order['delivery_address']); ?></p>
                    <hr>
                    <p><strong>Restaurant:</strong> <?php echo htmlspecialchars($order['restaurant_name']); ?></p>
                    <p><strong>Restaurant Address:</strong> <?php echo htmlspecialchars($order['restaurant_address']); ?></p>
                    
                    <form action="update_order_status.php" method="POST" class="status-update-form">
                        <input type="hidden" name="order_id" value="<?php echo $order['order_id']; ?>">
                        <div class="form-group">
                            <label for="status-<?php echo $order['order_id']; ?>">Update Status:</label>
                            <select name="status" id="status-<?php echo $order['order_id']; ?>">
                                <?php foreach ($order_statuses as $status): ?>
                                    <option value="<?php echo $status; ?>" <?php echo ($order['order_status'] === $status) ? 'selected' : ''; ?>>
                                        <?php echo ucwords($status); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button type="submit" class="btn-submit">Update</button>
                    </form>

                    <div class="delivery-controls">
                        <button class="btn-start-delivery" data-order-id="<?php echo $order['order_id']; ?>">Start Delivery</button>
                        <button class="btn-stop-delivery" data-order-id="<?php echo $order['order_id']; ?>" style="display: none;">Stop Delivery</button>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const locationWatchers = {};

    document.querySelectorAll('.btn-start-delivery').forEach(button => {
        button.addEventListener('click', () => {
            const orderId = button.dataset.orderId;
            
            if (!navigator.geolocation) {
                alert('Geolocation is not supported by your browser.');
                return;
            }

            button.disabled = true;
            document.querySelector(`.btn-stop-delivery[data-order-id="${orderId}"]`).style.display = 'inline-block';


            const watcherId = navigator.geolocation.watchPosition(
                (position) => {
                    const { latitude, longitude } = position.coords;
                    sendLocation(orderId, latitude, longitude);
                },
                (error) => {
                    console.error('Error getting location:', error);
                    alert('Error getting your location. Please ensure you have enabled location services.');
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 0
                }
            );

            locationWatchers[orderId] = watcherId;
        });
    });

    document.querySelectorAll('.btn-stop-delivery').forEach(button => {
        button.addEventListener('click', () => {
            const orderId = button.dataset.orderId;
            if (locationWatchers[orderId]) {
                navigator.geolocation.clearWatch(locationWatchers[orderId]);
                delete locationWatchers[orderId];
                button.style.display = 'none';
                document.querySelector(`.btn-start-delivery[data-order-id="${orderId}"]`).disabled = false;
                alert('Delivery stopped.');
            }
        });
    });

    function sendLocation(orderId, lat, lng) {
        fetch('/api/save_location.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                order_id: orderId,
                lat: lat,
                lng: lng
            })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                console.log(`Location updated for order ${orderId}`);
            } else {
                console.error('Failed to update location:', data.error);
            }
        })
        .catch(error => {
            console.error('Error sending location:', error);
        });
    }
});
</script>

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