<?php
session_start();
require_once '../db/config.php';

// Check if the user is a driver and is logged in
if (!isset($_SESSION['driver_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'driver') {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    $orderId = $data['order_id'] ?? null;
    $lat = $data['lat'] ?? null;
    $lng = $data['lng'] ?? null;

    if (!$orderId || !$lat || !$lng) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing required parameters.']);
        exit;
    }

    try {
        $pdo = db();
        // First, verify the driver is assigned to this order
        $stmt = $pdo->prepare("SELECT id FROM driver_assignments WHERE order_id = ? AND driver_id = ?");
        $stmt->execute([$orderId, $_SESSION['driver_id']]);
        $assignment = $stmt->fetch();

        if (!$assignment) {
            http_response_code(403);
            echo json_encode(['error' => 'You are not assigned to this order.']);
            exit;
        }

        // Update the order with the driver's location
        $stmt = $pdo->prepare("UPDATE orders SET driver_lat = ?, driver_lng = ? WHERE id = ?");
        $stmt->execute([$lat, $lng, $orderId]);

        echo json_encode(['success' => true]);
    } catch (PDOException $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
}
