with bookings as (
    select
        b.*,
        lag(b.ignition) over (
            partition by b.vehicle_id
            order by b.utc asc, b.eventid asc
        ) as previous_ignition
    from data.d8_booking b
)
select
    b.eventid,
    b.utc,
    b.vehicle_id,
    b.driver_id,
    b.key,
    b.ignition,
    b.previous_ignition,
    b.eventtype,
    b.state,
    b.odometer,
    st_y(b.geom) as latitude,
    st_x(b.geom) as longitude,
    b.payload,

    v.vrn as vehicle_vrn,
    v.vin as vehicle_vin,
    v.fleet_id as vehicle_fleet_id,

    d.firstname as driver_firstname,
    d.name as driver_lastname,
    left(trim(d.drivers_card), 14) as driver_card_number,
    d.fleet_id as driver_fleet_id,

    f.id as fleet_id,
    f.name as fleet_name,

    tp.id as telematic_provider_id,
    tp.name as telematic_provider_name
from bookings b
left join data.vehicle v
       on v.id = b.vehicle_id
left join data.driver d
       on d.id = b.driver_id
left join data.fleet f
       on f.id = coalesce(v.fleet_id, d.fleet_id)
left join data.telematic_provider tp
       on tp.id = v.telematic_provider_id
/*__FILTERS__*/
order by b.utc asc, b.eventid asc;
