<?php
require_once ROOT . FOLDER_CORE . '/auth.php';
require_once ROOT . FOLDER_CORE . '/class.php';
require_once ROOT . '/assets/conn/SQLConnex.php';

if($auth == 1) {
    
    $c = new SQLConnex();
    if(isset($_POST['eurotax_code']) && !empty($_POST['eurotax_code'])) {//Check variables values
        $eurotax_code = Statics::safe($_POST['eurotax_code']);
        $data['eurotax_code'] = $eurotax_code;
        $sql = 'SELECT E.EQTText
        FROM ADDITION AS A 
        INNER JOIN EQTEXT AS E ON A.ADDEQCode = E.EQTEQCode 
        WHERE A.ADDNatCode = ?
        AND A.ADDFlag = ?';
        $values = [$eurotax_code,  0];

        if(isset($_POST['date']) && !empty($_POST['date'])) {//Push this conditions if date exists
            $date = Statics::safe($_POST['date']);
            $data['date'] = $date;
            $sql .= ' AND A.ADDVAL <= ? AND (A.ADDVALUNTIL >= ? OR A.ADDVALUNTIL IS NULL)';
            array_push($values, $date, $date);
        }
        $sql .= ' ORDER BY E.EQTText DESC';

        $data['status'] = true;
        $data['request'] = 'Successful';
        $data['message'] = 'Rows not found';
        $stmt = sqlsrv_prepare($c->con, $sql, $values);
        if(sqlsrv_execute($stmt)) {
            if(sqlsrv_has_rows($stmt)) {
                unset($data['message']);//Remove message of not found
                $i = 0;
                while($row = sqlsrv_fetch_array($stmt)) {
                    $data['equipment'][$i]['title'] = $row['EQTText'];
                    $i++;
                }
            }
        }


        sqlsrv_close($c->con);
    } else {
        $data['status'] = false;
        $data['request'] = 'Inavlid request';
        $data['message'] = 'Eurotax code not found';
    }   
} else {
    $data['code'] = 'unauthorized_client';
    $data['message'] = 'Invalid authorization token';  
}

header("Content-type: application/json; charset=utf-8");
echo json_encode($data);

?>