-- Migration 011: Add mcu_patient_resume_status table

CREATE TABLE IF NOT EXISTS mcu_patient_resume_status (
    Mcu_PatientResumeStatusID           INT AUTO_INCREMENT PRIMARY KEY,
    Mcu_PatientResumeStatusPreregisterID INT NOT NULL,
    Mcu_PatientResumeStatusMcuID        INT NOT NULL,
    Mcu_PatientResumeStatusStatus       VARCHAR(15),              -- from mcu_resume.Mcu_ResumeStatus
    Mcu_PatientResumeStatusValidated    CHAR(1) DEFAULT 'N',      -- from mcu_resume.Mcu_ResumeValidation
    Mcu_PatientResumeStatusPublished    CHAR(1) DEFAULT 'N',      -- default N
    Mcu_PatientResumeSyncedAt           DATETIME,
    UNIQUE KEY uq_patient_mcu (Mcu_PatientResumeStatusPreregisterID, Mcu_PatientResumeStatusMcuID),
    INDEX idx_mcu_id (Mcu_PatientResumeStatusMcuID),
    INDEX idx_preregister_id (Mcu_PatientResumeStatusPreregisterID),
    INDEX idx_validated (Mcu_PatientResumeStatusValidated),
    INDEX idx_published (Mcu_PatientResumeStatusPublished)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


-- Update SP: tambah step 7 untuk mcu_patient_resume_status
DROP PROCEDURE IF EXISTS sp_generate_dashboard_data;

DELIMITER $$

CREATE PROCEDURE sp_generate_dashboard_data(IN p_mcu_id INT)
BEGIN

    -- ----------------------------------------------------------
    -- 1. mcu_patient (with age)
    -- ----------------------------------------------------------
    INSERT INTO mcu_patient (
        Mcu_PatientPreregisterID, Mcu_PatientMcuID, Mcu_PatientName,
        Mcu_PatientNIP, Mcu_PatientGender, Mcu_PatientDOB, Mcu_PatientAge,
        Mcu_PatientDepartment, Mcu_PatientDivision, Mcu_PatientPosisi,
        Mcu_PatientIsRegistered, Mcu_PatientOrderID, Mcu_PatientIsActive,
        Mcu_PatientSyncedAt
    )
    SELECT
        p.Mcu_PreregisterPatientsID, p.Mcu_PreregisterPatientsMgm_McuID,
        p.Mcu_PreregisterPatientsPatientName, p.Mcu_PreregisterPatientsNIP,
        p.Mcu_PreregisterPatientsGender, p.Mcu_PreregisterPatientsDOB,
        CAST(o.T_OrderHeaderM_PatientAge AS UNSIGNED),
        p.Mcu_PreregisterPatientsDepartment, p.Mcu_PreregisterPatientsDivisi,
        p.Mcu_PreregisterPatientsPosisi,
        p.Mcu_PreregisterPatientsIsRegistered, p.Mcu_PreregisterPatientsT_OrderHeaderID,
        p.Mcu_PreregisterPatientsIsActive, NOW()
    FROM cpone.mcu_preregister_patients p
    LEFT JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
    WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
    AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
    ON DUPLICATE KEY UPDATE
        Mcu_PatientName         = VALUES(Mcu_PatientName),
        Mcu_PatientAge          = VALUES(Mcu_PatientAge),
        Mcu_PatientIsRegistered = VALUES(Mcu_PatientIsRegistered),
        Mcu_PatientOrderID      = VALUES(Mcu_PatientOrderID),
        Mcu_PatientSyncedAt     = NOW();


    -- ----------------------------------------------------------
    -- 2. mcu_patient_schedule
    -- ----------------------------------------------------------
    INSERT INTO mcu_patient_schedule (
        Mcu_PatientSchedulePreregisterID, Mcu_PatientScheduleDate,
        Mcu_PatientScheduleIsActive, Mcu_PatientScheduleSyncedAt
    )
    SELECT
        p.Mcu_PreregisterPatientsID, DATE(o.T_OrderHeaderDate), 'Y', NOW()
    FROM cpone.mcu_preregister_patients p
    JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
    WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
    AND   p.Mcu_PreregisterPatientsT_OrderHeaderID > 0
    AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
    ON DUPLICATE KEY UPDATE
        Mcu_PatientScheduleSyncedAt = NOW();


    -- ----------------------------------------------------------
    -- 3. mcu_checkinout
    --    Satu baris per tanggal proses.
    -- ----------------------------------------------------------
    INSERT INTO mcu_checkinout (
        Mcu_CheckinoutCheckinoutID, Mcu_CheckinoutPreregisterID, Mcu_CheckinoutOrderID,
        Mcu_CheckinoutDate, Mcu_CheckinoutInTime, Mcu_CheckinoutOutTime,
        Mcu_CheckinoutNextDate, Mcu_CheckinoutIsActive, Mcu_CheckinoutSyncedAt, Mcu_CheckinoutMcuID
    )
    SELECT
        src.order_id,
        src.preregister_id,
        src.order_id,
        src.segment_date,
        TIME(src.checkin_dt),
        TIME(src.checkout_dt),
        CASE
            WHEN DATE(src.checkout_dt) = src.segment_date THEN NULL
            ELSE DATE(src.checkout_dt)
        END,
        'Y', NOW(), p_mcu_id
    FROM (
        SELECT
            o.T_OrderHeaderID AS order_id,
            p.Mcu_PreregisterPatientsID AS preregister_id,
            o.T_OrderHeaderDate AS header_dt,
            ev.segment_date,
            CASE
                WHEN ev.segment_date = DATE(o.T_OrderHeaderDate) THEN o.T_OrderHeaderDate
                ELSE MIN(ev.event_dt)
            END AS checkin_dt,
            MAX(ev.event_dt) AS checkout_dt
        FROM cpone.mcu_preregister_patients p
        JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
        JOIN (
            SELECT
                p2.Mcu_PreregisterPatientsID AS preregister_id,
                o2.T_OrderHeaderID AS order_id,
                o2.T_OrderHeaderDate AS checkin_dt,
                DATE(o2.T_OrderHeaderDate) AS segment_date,
                o2.T_OrderHeaderDate AS event_dt
            FROM cpone.mcu_preregister_patients p2
            JOIN cpone.t_orderheader o2 ON o2.T_OrderHeaderID = p2.Mcu_PreregisterPatientsT_OrderHeaderID
            WHERE p2.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
            AND   p2.Mcu_PreregisterPatientsT_OrderHeaderID > 0
            AND   p2.Mcu_PreregisterPatientsIsActive = 'Y'
            UNION ALL
            SELECT
                p2.Mcu_PreregisterPatientsID AS preregister_id,
                o2.T_OrderHeaderID AS order_id,
                o2.T_OrderHeaderDate AS checkin_dt,
                DATE(TIMESTAMP(s2.T_OrderSampleReceiveDate, s2.T_OrderSampleReceiveTime)) AS segment_date,
                TIMESTAMP(s2.T_OrderSampleReceiveDate, s2.T_OrderSampleReceiveTime) AS event_dt
            FROM cpone.mcu_preregister_patients p2
            JOIN cpone.t_orderheader o2 ON o2.T_OrderHeaderID = p2.Mcu_PreregisterPatientsT_OrderHeaderID
            JOIN cpone.t_ordersample s2
                ON  s2.T_OrderSampleT_OrderHeaderID = o2.T_OrderHeaderID
                AND s2.T_OrderSampleIsActive = 'Y'
            WHERE p2.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
            AND   p2.Mcu_PreregisterPatientsT_OrderHeaderID > 0
            AND   p2.Mcu_PreregisterPatientsIsActive = 'Y'
            AND   s2.T_OrderSampleReceiveDate IS NOT NULL
            AND   s2.T_OrderSampleReceiveTime IS NOT NULL
            UNION ALL
            SELECT
                p2.Mcu_PreregisterPatientsID AS preregister_id,
                o2.T_OrderHeaderID AS order_id,
                o2.T_OrderHeaderDate AS checkin_dt,
                DATE(TIMESTAMP(ts2.T_SamplingSoDoneDate, ts2.T_SamplingSoDoneTime)) AS segment_date,
                TIMESTAMP(ts2.T_SamplingSoDoneDate, ts2.T_SamplingSoDoneTime) AS event_dt
            FROM cpone.mcu_preregister_patients p2
            JOIN cpone.t_orderheader o2 ON o2.T_OrderHeaderID = p2.Mcu_PreregisterPatientsT_OrderHeaderID
            JOIN cpone.t_samplingso ts2
                ON  ts2.T_SamplingSoT_OrderHeaderID = o2.T_OrderHeaderID
                AND ts2.T_SamplingSoIsActive = 'Y'
            WHERE p2.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
            AND   p2.Mcu_PreregisterPatientsT_OrderHeaderID > 0
            AND   p2.Mcu_PreregisterPatientsIsActive = 'Y'
            AND   ts2.T_SamplingSoDoneDate IS NOT NULL
            AND   ts2.T_SamplingSoDoneTime IS NOT NULL
        ) ev
            ON ev.preregister_id = p.Mcu_PreregisterPatientsID
           AND ev.order_id = o.T_OrderHeaderID
        WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
        AND   p.Mcu_PreregisterPatientsT_OrderHeaderID > 0
        AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
        GROUP BY o.T_OrderHeaderID, p.Mcu_PreregisterPatientsID, o.T_OrderHeaderDate, ev.segment_date
    ) AS src
    ON DUPLICATE KEY UPDATE
        Mcu_CheckinoutOutTime  = VALUES(Mcu_CheckinoutOutTime),
        Mcu_CheckinoutNextDate = VALUES(Mcu_CheckinoutNextDate),
        Mcu_CheckinoutSyncedAt = NOW();


    -- ----------------------------------------------------------
    -- 4. mcu_station_progress — lab (dari t_ordersample)
    --    GROUP BY order+station supaya satu baris per pasien per station
    -- ----------------------------------------------------------
    INSERT INTO mcu_station_progress (
        Mcu_StationProgressOrderID, Mcu_StationProgressPreregisterID, Mcu_StationProgressMcuID,
        Mcu_StationProgressStationID, Mcu_StationProgressStationName, Mcu_StationProgressSource,
        Mcu_StationProgressCheckinDate,
        Mcu_StationProgressSamplingAt, Mcu_StationProgressReceiveAt, Mcu_StationProgressProcessAt,
        Mcu_StationProgressDoneAt, Mcu_StationProgressSyncedAt
    )
    SELECT
        o.T_OrderHeaderID,
        p.Mcu_PreregisterPatientsID,
        p_mcu_id,
        s.T_OrderSampleT_SampleStationID,
        ss.T_SampleStationName,
        'lab',
        DATE(o.T_OrderHeaderDate),
        NULLIF(MAX(TIMESTAMP(s.T_OrderSampleSamplingDate,   s.T_OrderSampleSamplingTime)),   '0000-00-00 00:00:00'),
        NULLIF(MAX(TIMESTAMP(s.T_OrderSampleReceiveDate,    s.T_OrderSampleReceiveTime)),    '0000-00-00 00:00:00'),
        NULLIF(MAX(TIMESTAMP(s.T_OrderSampleProcessingDate, s.T_OrderSampleProcessingTime)), '0000-00-00 00:00:00'),
        NULL,
        NOW()
    FROM cpone.mcu_preregister_patients p
    JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
    JOIN cpone.t_ordersample s  ON s.T_OrderSampleT_OrderHeaderID = o.T_OrderHeaderID AND s.T_OrderSampleIsActive = 'Y'
    JOIN cpone.t_samplestation ss ON ss.T_SampleStationID = s.T_OrderSampleT_SampleStationID
    WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
    AND   p.Mcu_PreregisterPatientsT_OrderHeaderID > 0
    AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
    GROUP BY o.T_OrderHeaderID, p.Mcu_PreregisterPatientsID, s.T_OrderSampleT_SampleStationID, ss.T_SampleStationName, o.T_OrderHeaderDate
    ON DUPLICATE KEY UPDATE
        Mcu_StationProgressSamplingAt = VALUES(Mcu_StationProgressSamplingAt),
        Mcu_StationProgressReceiveAt  = VALUES(Mcu_StationProgressReceiveAt),
        Mcu_StationProgressProcessAt  = VALUES(Mcu_StationProgressProcessAt),
        Mcu_StationProgressSyncedAt   = NOW();


    -- ----------------------------------------------------------
    -- 5. mcu_station_progress — nonlab (dari t_samplingso)
    -- ----------------------------------------------------------
    INSERT INTO mcu_station_progress (
        Mcu_StationProgressOrderID, Mcu_StationProgressPreregisterID, Mcu_StationProgressMcuID,
        Mcu_StationProgressStationID, Mcu_StationProgressStationName, Mcu_StationProgressSource,
        Mcu_StationProgressCheckinDate,
        Mcu_StationProgressSamplingAt, Mcu_StationProgressReceiveAt, Mcu_StationProgressProcessAt,
        Mcu_StationProgressDoneAt, Mcu_StationProgressSyncedAt
    )
    SELECT
        o.T_OrderHeaderID,
        p.Mcu_PreregisterPatientsID,
        p_mcu_id,
        ts.T_SamplingSoT_SampleStationID,
        ss.T_SampleStationName,
        'nonlab',
        DATE(o.T_OrderHeaderDate),
        NULL,
        NULL,
        NULLIF(MAX(TIMESTAMP(ts.T_SamplingSoProcessDate, ts.T_SamplingSoProcessTime)), '0000-00-00 00:00:00'),
        NULLIF(MAX(TIMESTAMP(ts.T_SamplingSoDoneDate,    ts.T_SamplingSoDoneTime)),    '0000-00-00 00:00:00'),
        NOW()
    FROM cpone.mcu_preregister_patients p
    JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
    JOIN cpone.t_samplingso ts  ON ts.T_SamplingSoT_OrderHeaderID = o.T_OrderHeaderID AND ts.T_SamplingSoIsActive = 'Y'
    JOIN cpone.t_samplestation ss ON ss.T_SampleStationID = ts.T_SamplingSoT_SampleStationID
    WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
    AND   p.Mcu_PreregisterPatientsT_OrderHeaderID > 0
    AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
    GROUP BY o.T_OrderHeaderID, p.Mcu_PreregisterPatientsID, ts.T_SamplingSoT_SampleStationID, ss.T_SampleStationName, o.T_OrderHeaderDate
    ON DUPLICATE KEY UPDATE
        Mcu_StationProgressProcessAt = VALUES(Mcu_StationProgressProcessAt),
        Mcu_StationProgressDoneAt    = VALUES(Mcu_StationProgressDoneAt),
        Mcu_StationProgressSyncedAt  = NOW();


    -- ----------------------------------------------------------
    -- 6. mcu_patient_resume_status (dari mcu_resume)
    -- ----------------------------------------------------------
    INSERT INTO mcu_patient_resume_status (
        Mcu_PatientResumeStatusPreregisterID, Mcu_PatientResumeStatusMcuID,
        Mcu_PatientResumeStatusStatus, Mcu_PatientResumeStatusValidated,
        Mcu_PatientResumeStatusPublished, Mcu_PatientResumeSyncedAt
    )
    SELECT
        p.Mcu_PreregisterPatientsID,
        p_mcu_id,
        r.Mcu_ResumeStatus,
        r.Mcu_ResumeValidation,
        'N',
        NOW()
    FROM cpone.mcu_preregister_patients p
    JOIN cpone.t_orderheader o ON o.T_OrderHeaderID = p.Mcu_PreregisterPatientsT_OrderHeaderID
    LEFT JOIN cpone.mcu_resume r ON r.Mcu_ResumeT_OrderHeaderID = o.T_OrderHeaderID AND r.Mcu_ResumeIsActive = 'Y'
    WHERE p.Mcu_PreregisterPatientsMgm_McuID = p_mcu_id
    AND   p.Mcu_PreregisterPatientsT_OrderHeaderID > 0
    AND   p.Mcu_PreregisterPatientsIsActive = 'Y'
    ON DUPLICATE KEY UPDATE
        Mcu_PatientResumeStatusStatus = VALUES(Mcu_PatientResumeStatusStatus),
        Mcu_PatientResumeStatusValidated = VALUES(Mcu_PatientResumeStatusValidated),
        Mcu_PatientResumeSyncedAt = NOW();

END $$

DELIMITER ;
