<?php
    include "../db/headerApi.php";
    include "../db/connection_main.php";

    $json = file_get_contents('php://input');
    $data = json_decode($json);

    if (!empty($data)) {
        $sql = "SELECT a.stage_pos, b.employee_name pic, a.action,
                       to_char(a.action_date, 'DD/MON/YYYY HH24:MI') action_date, null remarks
                  FROM ytycustom.ple_approval_stages a, production.employee_master b
                 WHERE a.approver = b.emp_id
                   AND a.header_id = :ID
                 UNION
                SELECT a1.from_stage_pos stage_pos, b1.employee_name AS pic,
                       'REQ. INFO' action,
                       to_char(a1.request_date, 'DD/MON/YYYY HH24:MI') request_date,
                       CASE
                            WHEN info_desc IS NULL THEN
                            'Awaiting response from stage ' || a1.to_stage_pos
                       ELSE
                            'Request Completed (' || a1.from_stage_pos || ' to ' ||
                            a1.to_stage_pos || ')'
                       END remarks
                  FROM ytycustom.ple_information a1, production.employee_master b1
                 WHERE a1.request_by = b1.emp_id
                   AND a1.header_id = :ID
              ORDER BY stage_pos desc, action_date desc";

        $sqlarr = oci_parse($dbcon , $sql);
        oci_bind_by_name($sqlarr, ':ID', $data->ID);
        $r = oci_execute($sqlarr);
        oci_fetch_all($sqlarr, $rows_main, null, null, OCI_FETCHSTATEMENT_BY_ROW);

        $resMsg = "OK";

        if (!$r) {
            $e = oci_error($sqlarr);
            $resMsg = json_encode($e['message']);
        } 
    
    } else {
        $resMsg = "Wrong parameters.";
    }

    $result[] = [
        "message" => $resMsg,
        "data" => $rows_main
    ];

    print json_encode($result, JSON_NUMERIC_CHECK);
?>