<?php



require_once '../../config.php'; // Include configuration file



require_once '../../meekrodb.2.4.class.php';



require_once 'response.php';



require_once 'endpoint_map.php';







// Set database credentials from config.php



DB::$host = $host;



DB::$user = $username;



DB::$password = $password;



DB::$dbName = $database;







$table = 'glance_scroll';



$profileTable = 'glance_scroll_profile';



$ledTable = 'selected_coins';



$timeZone = new DateTimeZone($defaultMap["timeZone"]);







if ($_SERVER["REQUEST_METHOD"] == "POST") {



    $jsonData = file_get_contents('php://input');



    $data = json_decode($jsonData, true);



    if ($data !== null) {



        $macAddress = json_decode($data["macAddress"]);



        $profile = json_decode($data["profile"]);



        if (false === filter_var($macAddress, FILTER_VALIDATE_MAC)) {



            return response(400, 'Invalid MAC Address Entered. MAC address should be exactly 17 characters long. The MAC address should be in the format XX:XX:XX:XX:XX:XX');



        } else {



            $result = DB::query("SELECT * FROM $table where MAC = %s", $macAddress);



            if(empty($result)) {



                // check if its a SCROLL device



                $result = DB::query("SELECT * FROM $ledTable where dev_mac = %s", $macAddress);



                if(!empty($result)) {



                    return response(400, 'This appears to be a GLANCE device. Please use the GLANCE CLASSIC option from the Home screen.');



                }



                return response(404, 'Unregistered MAC Address. Please Double Check Entry - Digits Range from 0-9 and A-F. Contact us at glance-led.com if issues persist.');



            } else {



                $selections = "";



                $endPoint = "";



                // Parse Stock



                $stock = json_decode($data["finance"], true)["stock"];



                if(!empty($stock)) {



                    foreach ($stock as $key => $value) {



                        $selections = $selections . "!" . $value["Ticker"] . ",";



                    }



                    $endPoint = $endPointMap["!"] . ",";



                }



                // Parse Crypto



                $crypto = json_decode($data["finance"], true)["crypto"];



                if(!empty($crypto)) {



                    foreach ($crypto as $key => $value) {



                        $selections = $selections . "*" . $value["Ticker"] . ",";



                    }



                    $endPoint = $endPoint . $endPointMap["*"] . ",";



                }



                // Parse Top Movers



                $topMovers = json_decode($data["finance"], true)["topMovers"];



                if(!empty($topMovers)) {



                    foreach ($topMovers as $item) {



                        $endPoint = $endPoint . $topMoversMap[$item] . ",";



                    }



                }



                // Parse standings



                $standings = json_decode($data["sports"], true)["standings"];



                if(!empty($standings)) {



                    foreach ($standings as $item) {



                        $endPoint = $endPoint . $standingMap[$item] . ",";



                    }



                }



                // Parse game/sport



                $game = json_decode($data["sports"], true)["game"];



                if(!empty($game)) {



                    foreach ($game as $item) {



                        $endPoint = $endPoint . $gameMap[$item] . ",";



                    }



                }



                // Parse team



                $team = json_decode($data["sports"], true)["team"];



                if(!empty($team)) {



                    foreach ($team as $item) {



                        $selections = $selections . "^" . $item . ",";



                    }



                    $endPoint = $endPoint . $endPointMap["^"] . ",";



                }







                // Parse Lifestyle



                $lifestyle = json_decode($data["lifestyle"], true);



                $worldClock = json_decode($data["lifestyle"], true)["worldClock"];



                if(!empty($worldClock)) {



                    foreach ($worldClock as $item) {



                       $selections = $selections . "}" . $item . ",";



                    }



                    $endPoint = $endPoint . $endPointMap["}"] . ",";



                }



                $weather = json_decode($data["lifestyle"], true)["weather"];



                $weatherUnit = json_decode($data["lifestyle"], true)["weatherUnit"];



                if(!empty($weather)) {



                    foreach ($weather as $item) {



                       $selections = $selections . "_" . $item . "|" . ($weatherUnit?"C":"F") . ",";



                    }



                    $endPoint = $endPoint . $endPointMap["_"] . ",";



                }



                $youtube = json_decode($data["lifestyle"], true)["youtube"];



                $instagram = json_decode($data["lifestyle"], true)["instagram"];



                if(!empty($youtube) || !empty($instagram)) {



                    if(!empty($youtube)) {



                        $selections = $selections . (str_starts_with($youtube, "@")?"":"@") . $youtube . "|Youtube,";



                    }



                    if(!empty($instagram)) {



                        $selections = $selections . (str_starts_with($instagram, "@")?"":"@") . $instagram . "|Instagram,";



                    }



                    $endPoint = $endPoint . $endPointMap["@"] . ",";



                }



                $pb = json_decode($data["lifestyle"], true)["powerBall"];



                $mm = json_decode($data["lifestyle"], true)["megaMillion"];



                if($pb || $mm) {



                    if($pb) {



                        $selections = $selections . "-PB,";



                    }



                    if($mm) {



                        $selections = $selections . "-MM,";



                    }



                    $endPoint = $endPoint . $endPointMap["-"] . ",";



                }







                // Parse Fun



                $todayInHistory = json_decode($data["fun"], true)["todayInHistory"];



                $dailyFacts = json_decode($data["fun"], true)["dailyFacts"];



                $greatQuotes = json_decode($data["fun"], true)["greatQuotes"];



                if($todayInHistory || $dailyFacts || $greatQuotes) {



                    if($todayInHistory) {



                        $selections = $selections . "+TIAH.php,";



                    }



                    if($dailyFacts) {



                        $selections = $selections . "+FACT.php,";



                    }



                    if($greatQuotes) {



                        $selections = $selections . "+QUOTE.php,";



                    }



                    $endPoint = $endPoint . $endPointMap["+"] . ",";



                }



                $learnNewLanguage = json_decode($data["fun"], true)["learnNewLanguage"];



                $trivia = json_decode($data["fun"], true)["trivia"];



                $wordOfTheDay = json_decode($data["fun"], true)["wordOfTheDay"];



                if(!empty($learnNewLanguage) || $trivia || $wordOfTheDay) {



                    if(!empty($learnNewLanguage) && !empty($learnNewLanguage["value"])) {



                        $selections = $selections . "{LNL.php?in=" . $learnNewLanguage["value"] . ",";



                    }



                    if($trivia) {



                        $selections = $selections . "{TRIVIA.php,";



                    }



                    if($wordOfTheDay) {



                        $selections = $selections . "{WOD.php,";



                    }



                    $endPoint = $endPoint . $endPointMap["{"] . ",";



                }



                $flagOfTheDay = json_decode($data["fun"], true)["flagOfTheDay"];



                if($flagOfTheDay) {



                    $endPoint = $endPoint . $endPointMap["FOD"] . ",";



                }



                //Parse News



                if(array_key_exists("world", json_decode($data["news"], true)) && json_decode($data["news"], true)["world"]) {



                    $endPoint = $endPoint . $endPointMap["WN"] . ",";



                }



                if(array_key_exists("finance", json_decode($data["news"], true)) && json_decode($data["news"], true)["finance"]) {



                    $endPoint = $endPoint . $endPointMap["FN"] . ",";



                }



                if(array_key_exists("sports", json_decode($data["news"], true)) && json_decode($data["news"], true)["sports"]) {



                    $endPoint = $endPoint . $endPointMap["SN"] . ",";



                }



                if(array_key_exists("ipo", json_decode($data["news"], true)) && json_decode($data["news"], true)["ipo"]) {



                    //$endPoint = $endPoint . $endPointMap["IN"] . ",";



                }



                // Parse Freetext



                $freetext = json_decode($data["freetext"], true);



                if(!empty($freetext)) {



                    $freeTextSelection = "";



                    foreach ($freetext as $item) {



                        if(!empty($item["text"])) {



                        $color = !empty($item["color"]) ? $item["color"] : "w";



                          $freeTextSelection .= "CM_" . $item["text"] . "|" . $color . ",";





                        }



                    }



                    if(!empty($freeTextSelection)) {



                        $selections = $selections . $freeTextSelection;



                        $endPoint = $endPoint . $endPointMap["CM_"] . ",";

                    }

                    }

                // Parse Gif's

                $gifs = json_decode($data["gif"], true);

                if(!empty($gifs)) {

                    foreach ($gifs as $item) {

                        $endPoint = $endPoint . $item . ",";

                    }

                }

                // Parse Settings



                $settings = json_decode($data["settings"], true);



                if(array_key_exists("timezone", $settings) && !empty($settings["timezone"]["value"])) {



                    $selections = $selections . "tz_" . $settings["timezone"]["value"] . ",";



                } else {



                    return response(400, 'The timezone is not set. You can go to Settings and set the timezone.');



                }



                $ledBrightness = $settings["ledBrightness"];



                if(!empty($ledBrightness)) {



                    $selections = $selections . "br_" . $ledBrightness . ",";



                }



                $scrollSpeed = $settings["scrollSpeed"];



                if(!empty($scrollSpeed)) {



                    $selections = $selections . "ss_" . $scrollSpeed . ",";



                }



                $sleepStartTime = $settings["startTime"];



                if(!empty($sleepStartTime)) {



                    $sleepStartTime = new DateTime($sleepStartTime);



                    $sleepStartTime->setTimeZone($timeZone);



                    $selections = $selections . "st_" . $sleepStartTime->format('H:i') . ",";



                }



                $sleepEndTime = $settings["endTime"];



                if(!empty($sleepEndTime)) {



                    $sleepEndTime = new DateTime($sleepEndTime);



                    $sleepEndTime->setTimeZone($timeZone);



                    $selections = $selections . "se_" . $sleepEndTime->format('H:i') . ",";



                }







                // trim trailing comma



                $selections = substr($selections, 0, -1);



                $endPoint = substr($endPoint, 0, -1);







                // Parse Profile



                $profileNames = $data["profileNames"];



$profileTimes = "";



$profileTimesRequest = json_decode($data["profileTimes"], true);



if(!empty($profileTimesRequest)) {



    $profileItems = Array();



    foreach ($profileTimesRequest as $item) {



        $profileStartTime = $item["startTime"];



        if(!empty($profileStartTime)) {



            // Convert profile start time to Eastern Time



            $profileStartTime = new DateTime($profileStartTime);



            $profileStartTime->setTimezone($timeZone);



        }



        $profileDays = Array();



        foreach($profileDayMap as $profileDay) {



            if($item[substr($profileDay, 0, 3)]) {



                array_push($profileDays, $profileDay);



            }



        }



        if(!empty($profileDays)) {



            array_push($profileItems, Array(



                "profile_id"=> $item["profile"],



                "time" => (empty($profileStartTime) ? "" : $profileStartTime->format('H:i')),



                "days" => $profileDays



            ));



        }



    }



    if(!empty($profileItems)) {



        $profileTimes = json_encode(Array("profiles" => $profileItems), true);



    }



}







                // always update db for default profile 1



                if($profile == 1) {



                    $result = DB::update($table



                        , array('Selections' => $selections, 'EndPoint' => $endPoint, 'needsUpdate' => 'T')



                        , "MAC = %s and PROFILE = %i", $macAddress, $profile);



                } else { // update or insert db for other profiles



                    $result = DB::insertUpdate($table



                        , array('MAC' => $macAddress,



                            'Selections' => $selections,



                            'EndPoint' => $endPoint,



                            'needsUpdate' => 'T',



                            'Profile' => $profile));



                }







                // First, check if the MAC address exists in the database



                $exists = DB::queryFirstField("SELECT MAC FROM glance_scroll_profile WHERE MAC = %s", $macAddress);







                if ($exists) {



                    // If the MAC address exists, update the profile



                    $updateResult = DB::update($profileTable,



                        array('Profile' => $profile, 'needsUpdate' => 'T',



                            'profileNames' => $profileNames, 'profileTimes' => $profileTimes), "MAC = %s", $macAddress);



                } else {



                    // If the MAC address does not exist, insert the new profile



                    $insertResult = DB::insert($profileTable,



                        array('MAC' => $macAddress, 'Profile' => $profile, 'needsUpdate' => 'T',



                            'profileNames' => $profileNames, 'profileTimes' => $profileTimes));



                }







                // Parse DB transaction response



                if (DB::affectedRows() >= 1) {



                    return response(200, 'Update successful.');



                } else {



                    return response(200, 'Request completed.');



                }



            }



        }



    } else {



        return response(400, 'Invalid data.');



    }



}



?>

