<?php
    include "../db/headerApi.php";
    include "../db/connection_main.php";

    $json = file_get_contents('php://input');
    $data = json_decode($json);

    $sql = "SELECT period_name id, period_name text
              FROM APPS.YTY_G_PRC_PERIOD_LOV
             WHERE trunc(start_date, 'YEAR') >= trunc(add_months(trunc(SYSDATE), -12), 'YEAR')
          ORDER BY start_date DESC";

    $sqlarr = oci_parse($dbcon , $sql);
    $r = oci_execute($sqlarr);
    $resMsg = "OK";

    if (!$r) {
         $e = oci_error($sqlarr);
         $resMsg = json_encode($e['message']);
         goto finalStep;
    }
    oci_fetch_all($sqlarr, $rows_main, null, null, OCI_FETCHSTATEMENT_BY_ROW);

    $sql = "SELECT to_char(ADD_MONTHS(SYSDATE, 0), 'MON-RR') current_period
              FROM dual";

    $sqlarr = oci_parse($dbcon , $sql);
    $r = oci_execute($sqlarr);
    $resMsg = "OK";

    if (!$r) {
         $e = oci_error($sqlarr);
         $resMsg = json_encode($e['message']);
         goto finalStep;
    }
    oci_fetch_all($sqlarr, $rows_curr, null, null, OCI_FETCHSTATEMENT_BY_ROW);
    $current_period = [ "ID" => $rows_curr[0]["CURRENT_PERIOD"], "TEXT" => $rows_curr[0]["CURRENT_PERIOD"] ]; 

finalStep:
    $result[] = [
        "message" => $resMsg,
        "data" => $rows_main,
        "current" => $current_period
    ];

    print json_encode($result);
?>