-- Add hourly_rate to labour_entries to capture wage at time of entry
ALTER TABLE labour_entries ADD COLUMN hourly_rate DECIMAL(10, 2) DEFAULT NULL AFTER hours;

-- Backfill hourly_rate from employee_wages
UPDATE labour_entries le
JOIN (
    SELECT ew1.employee_id, ew1.hourly_rate, ew1.effective_date
    FROM employee_wages ew1
    WHERE ew1.effective_date = (
        SELECT MAX(ew2.effective_date)
        FROM employee_wages ew2
        WHERE ew2.employee_id = ew1.employee_id
    )
) latest_wage ON le.employee_id = latest_wage.employee_id
SET le.hourly_rate = latest_wage.hourly_rate
WHERE le.hourly_rate IS NULL;
