<?php

    header('Content-Type: application/json');
    header("Access-Control-Allow-Origin: *");
    
    $sort = $_GET["s"];  // get sort type
    $asc = $_GET["a"];  // get sort type

    require '../php/database.php';

    if ($asc == 1) {
        $query = sprintf("SELECT schedules.scheduleID, schedules.scheduleTypeID, schedules.pinID, schedules.offOn, schedules.schName, schedules.start, schedules.sun, schedules.mon, schedules.tue, schedules.wed, schedules.thu, schedules.fri, schedules.sat, schedules.repeatDays, schedules.enabled, schedules.schEmail, schedules.schAlert, scheduleType.type, pinsAvailable.name, pinsAvailable.iconID, dosingSchedules.mL
        FROM schedules
        LEFT JOIN scheduleType
        ON scheduleType.scheduleTypeID = schedules.scheduleTypeID
        LEFT JOIN pinsAvailable
        ON pinsAvailable.pinID = schedules.pinID
        LEFT JOIN dosingSchedules
        ON dosingSchedules.scheduleID = schedules.scheduleID
        ORDER BY `{$sort}` ASC, `{$sort}` * 1 ASC");
        // ORDER BY LENGTH(`{$sort}`), `{$sort}` ASC");
        // ORDER BY binray_not_needed_column ASC , `{$sort}` ASC");
    }
    else {
        $query = sprintf("SELECT schedules.scheduleID, schedules.scheduleTypeID, schedules.pinID, schedules.offOn, schedules.schName, schedules.start, schedules.sun, schedules.mon, schedules.tue, schedules.wed, schedules.thu, schedules.fri, schedules.sat, schedules.repeatDays, schedules.enabled, schedules.schEmail, schedules.schAlert, scheduleType.type, pinsAvailable.name, pinsAvailable.iconID, dosingSchedules.mL
        FROM schedules
        LEFT JOIN scheduleType
        ON scheduleType.scheduleTypeID = schedules.scheduleTypeID
        LEFT JOIN pinsAvailable
        ON pinsAvailable.pinID = schedules.pinID
        LEFT JOIN dosingSchedules
        ON dosingSchedules.scheduleID = schedules.scheduleID
        ORDER BY `{$sort}` DESC, `{$sort}` * 1 DESC");
        // ORDER BY LENGTH(`{$sort}`), `{$sort}` DESC");
        // ORDER BY binray_not_needed_column DESC , `{$sort}` DESC");
    } 
    //execute query
    $result = $mysqli->query($query);

    //loop through the returned data
    $dataWindow = array();
    foreach ($result as $row) {
        $dataWindow[] = $row;
    }

    print json_encode($dataWindow);
    //free memory associated with result
    $result->close();

    //close connection
    $mysqli->close();