-- V6__init_report_views.sql (MySQL)
-- Report views with MySQL date functions

CREATE OR REPLACE VIEW v_project_hours AS
SELECT
    te.epc_project_id AS project_id,
    p.project_code,
    p.name AS project_name,
    te.entry_date,
    YEAR(te.entry_date)  AS `year`,
    MONTH(te.entry_date) AS `month`,
    WEEK(te.entry_date)  AS `week`,
    u.discipline,
    u.department,
    te.entry_type,
    SUM(te.hours) AS total_hours,
    COUNT(DISTINCT te.timesheet_id) AS timesheet_count
FROM timesheet_entries te
JOIN timesheets ts ON te.timesheet_id = ts.id
JOIN users u ON ts.user_id = u.id
LEFT JOIN projects p ON te.epc_project_id = p.id
WHERE ts.status = 'APPROVED'
GROUP BY te.epc_project_id, p.project_code, p.name,
         te.entry_date, YEAR(te.entry_date),
         MONTH(te.entry_date), WEEK(te.entry_date),
         u.discipline, u.department, te.entry_type;

CREATE OR REPLACE VIEW v_wbs_hours AS
SELECT
    cw.project_id,
    cw.wbs_code,
    cw.level AS wbs_level,
    cw.name AS wbs_name,
    cw.discipline,
    SUM(te.hours) AS total_hours,
    COUNT(DISTINCT ts.user_id) AS user_count
FROM timesheet_entries te
JOIN timesheets ts ON te.timesheet_id = ts.id
JOIN canonical_wbs cw ON te.canonical_wbs_id = cw.id
WHERE ts.status = 'APPROVED'
GROUP BY cw.project_id, cw.wbs_code, cw.level, cw.name, cw.discipline;
