<?php
  class iCrewTrackerData extends CodonData {
    public static function downloadIVAOAPIData($file_name_ivao)
    {
        echo "Downloading API Data from IVAO...<br>";
        $file   = new CodonWebService();
        $contents = file_get_contents('https://api.ivao.aero/getdata/whazzup');

        //save new file to server
        $file = fopen($file_name_ivao, "w");
        fwrite($file, $contents);
        fclose($file);
        echo "SUCCESS! Data downloaded and ready to be used. " . filesize($file_name_ivao) . " bytes <br>";
    }

    public static function downloadVATSIMAPIData($file_name_vatsim)
    {
        echo "Downloading API Data from VATSIM...<br>";
        $file   = new CodonWebService();
        $contents = file_get_contents('http://info.vroute.net/vatsim-data.txt');

        //save new file to server
        $file = fopen($file_name_vatsim, "w");
        fwrite($file, $contents);
        fclose($file);
        echo "SUCCESS! Data downloaded and ready to be used. " . filesize($file_name_vatsim) . " bytes <br>";
    }

    public static function calculateOnlineTime($fpTime) {
      $now = date('YmdHis');
      $start = strtotime($fpTime);
      $end = strtotime($now);
      $datetime1 = new DateTime(date("Y-m-d H:i:s", $start));
      $datetime2 = new DateTime(date("Y-m-d H:i:s", $end));
      $interval = $datetime1->diff($datetime2);

      $output = array('formatted_time' => $interval->format('%H:%I'), 'time_in_mins' => $interval->format('%i'));

      // echo $interval->format(' %Hh %im');
      return $output;

    }


    public static function getPilotData_IVAO($VID, $field) {
      // Pilot identification from VID to VA match.
      if($field == '') {
        $field = 2;
      }
      $sql = "SELECT `pilotid` FROM `".TABLE_PREFIX."fieldvalues` WHERE `fieldid` = $field AND `value` = $VID";
      $res = DB::get_row($sql);
      // print_r($res);
      $pilotdata = PilotData::getPilotData($res->pilotid);
      return $pilotdata;
    }

    public static function getPilotData_VATSIM($VID, $field) {
      // Pilot identification from VID to VA match.
      if($field == '') {
        $field = 1;
      }
      $sql = "SELECT `pilotid` FROM `".TABLE_PREFIX."fieldvalues` WHERE `fieldid` = $field AND `value` = $VID";
      $res = DB::get_row($sql);
      // print_r($res);
      $pilotdata = PilotData::getPilotData($res->pilotid);
      return $pilotdata;
    }

    public static function checkPilot_IVAO($VID, $field = 2) {
      $sql = "SELECT `pilotid` FROM `".TABLE_PREFIX."fieldvalues` WHERE `fieldid` = $field AND `value` = $VID";
      $res = DB::get_row($sql);

      if($res->pilotid == '') {
        return 0; // No matches found for Pilot's VID
      } else {
        return 1; // Pilot's VID found in DB!
      }
    }

    public static function checkPilot_VATSIM($CID, $field = 1) {
      $sql = "SELECT `pilotid` FROM `".TABLE_PREFIX."fieldvalues` WHERE `fieldid` = $field AND `value` = $CID";
      $res = DB::get_row($sql);

      if($res->pilotid == '') {
        return 0; // No matches found for Pilot's VID
      } else {
        return 1; // Pilot's VID found in DB!
      }
    }


    public static function positionreport($pilotid, $flightnumber, $latitude,$longitude, $heading, $trueheading,$altitude, $groundspeed, $departureicao,$arrivalicao, $phase, $arrivaltime,$departuretime, $distanceremaining, $route, $timeremaining, $aircraft, $onlinenetwork) {

          $pilotdet = PilotData::getPilotData($pilotid);

          $phases = array(
        "Preflight",
        "Pushing Back",
        "Taxiing to Runway",
        "Taking Off",
        "Climbing",
        "Cruising",
        "Descending",
        "Approaching",
        "Final Approach",
        "Landing",
        "Taxiing to Gate",
        "Awaiting Arrival", /* An intermediary state when smartCARS has detected the aircraft is ready to arrive but the pilot hasn't clicked "End Flight" yet. */
        "Arrived"
      );


          $lat = str_replace(",", ".", $latitude);
          $lon = str_replace(",", ".", $longitude);

          $lat = doubleval($lat);
          $lon = doubleval($lon);

          if($lon < 0.005 && $lon > -0.005)
              $lon = 0;

          if($lat < 0.005 && $lat > -0.005)
              $lat = 0;



          $fields = array(
              'pilotid' =>$dbid,
              'flightnum' =>$flightnumber,
              'pilotname' => $pilotdet->firstname . " " . $pilotdet->lastname,
              'aircraft' =>$aircraft,
              'lat' =>$lat,
              'lng' =>$lon,
              'heading' =>$heading,
              'alt' =>$altitude,
              'gs' =>$groundspeed,
              'depicao' =>$departureicao,
              'arricao' =>$arrivalicao,
              'deptime' =>$departuretime,
              'arrtime' =>$arrivaltime,
              'route' =>$route,
              'distremain' =>$distanceremaining,
              'timeremaining' =>$timeremaining,
              'phasedetail' => "undefined",
              'online' => $onlinenetwork,
              'client' =>'iCrewTracker<b>PRO</b> v0.1',
          );

          ACARSData::UpdateFlightData($pilotid, $fields);
          return "POSREP Filed!";
    }



        public static function updateOnlineFlightTime($id, $time) {
            $sql = "UPDATE `icrew_tracker_currentflights` SET `online_time` = '$time' WHERE `id` = $id";
            DB::query($sql);

            echo "<br>FLIGHTTIME updated!<br>";
          }

          public static function resetOnlineFlights_post_PIREP($id) {
            $sql = "DELETE FROM `icrew_tracker_currentflights` WHERE `id` = '$id'";
            $ret = DB::query($sql);
            if($ret == 1) {
              // DiscordData::deliver('iCrewTracker table reset!');
              return 1;
            }
          }

          public static function filepirep($pilotid, $code, $flightnumber, $routeid, $bidid, $departureicao, $arrivalicao, $route, $aircraft, $load, $flighttime, $landingrate, $comments, $fuelused, $log) {
              $log = str_replace('[', '*[', $log);
              $log = str_replace('\\r', '', $log);
              $log = str_replace('\\n', '', $log);
              $pirepdata = array(
                      'pilotid' => $pilotid,
                      'code' => $code,
                      'flightnum' => $flightnumber,
                      'depicao' => $departureicao,
                      'arricao' => $arrivalicao,
                      'route' => $route,
                      'aircraft' => $aircraft,
                      'load' => $load,
                      'flighttime' => $flighttime,
                      'landingrate' => $landingrate,
                      'submitdate' => date('Y-m-d H:i:s'),
                      'comment' => $comments,
                      'fuelused' => $fuelused,
                      'source' => 'iCrewTracker<strong>PRO</strong> v0.5',
                      'log' => $log
                  );

              $ret = ACARSData::FilePIREP($pilotid, $pirepdata);

              // print_r($pirepdata);


              $sql = "UPDATE " . TABLE_PREFIX . "acarsdata SET `gs` = '0', `distremain` = '0', `timeremaining` = '0:00', `phasedetail` = 'Arrived', `arrtime` = CURRENT_TIMESTAMP WHERE `pilotid` = '$pilotid'";
              $ret = DB::query($sql);
              if($ret == 1) {
                // DiscordData::deliver('phpvms_acarsdata reset!');
              }

              $sql = "DELETE FROM " . TABLE_PREFIX . "bids WHERE bidid = '$bidid'";
              $ret = DB::query($sql);
              if($ret == 1) {
                // DiscordData::deliver('Bid deleted');
              }




              DiscordData::deliver("PIREP filed successfully for $code $flightnumber!");
              return true;
            }


        public static function getOnlineFlightData($callsign) {

          $sql = "SELECT * FROM  `icrew_tracker_currentflights` WHERE `callsign` = '$callsign'";
          $res = DB::get_results($sql);

          if($res == '') {
            return 0;
          } else {
            return $res;
          }
        }



        public static function checkOnlineFlightsOnDB($online_flights = 0) {

          $sql = "SELECT * FROM `icrew_tracker_currentflights` WHERE `network` = 'IVAO'";
          $result = DB::get_results($sql);

          if($result != '') {
            echo "<br>Checking icrew_tracker_currentflights table....<br>";
            foreach ($result as $flight) {
              echo $flight->callsign;

              //if flight is live

              if (in_array($flight->callsign, $online_flights)) {
                echo " - Flight found online!<br>";

              } else {
                echo " - Flight not found ONLINE, must have ended....filing PIREP<br>";
                // DiscordData::deliver("@everyone Filing PIREP for $flight->callsign through cron!");
                $flightdata = self::getOnlineFlightData($flight->callsign);
                foreach ($flightdata as $flightdata) {
                echo "Flight Bid ID (check if bid is there on phpvms_bids) : ".$flightdata->bidid."<br>";
                if($flightdata == '') {
                  DiscordData::deliver("@everyone ERROR in Filing PIREP for $flight->callsign, no data found in `icrew_tracker_currentflights`");
                } else {
                  //Get Schedule Data

                  $bid = SchedulesData::getBid($flightdata->bidid);
                  if($bid == '') {
                    echo "ERROR: BID NOT FOUND! Unable to file PIREP <br>";
                  } else {
                      echo "Bid found! <br> ";

                  $schedules = SchedulesData::getSchedule($bid->routeid);
                  $pilotid = $flightdata->pilotid;
                  $aircraft = $schedules->aircraftid;
                  $code = $schedules->code;
                  $flightnumber = $schedules->flightnum;
                  $routeid = $schedules->routeid;
                  $bidid = $flightdata->bidid;
                  $departureicao = $schedules->depicao;
                  $arrivalicao = $schedules->arricao;
                  $route = $flightdata->route;
                  $load = "250"; // RANDOM
                  $flighttime = $flightdata->online_time;
                  $landingrate = "0";
                  $comments = "TEST FLIGHT! Tracked by iCrewTrackerPRO. Cool module, right?";
                  $fuelused = "2000"; // RANDOM
                  $log = "iCrewTracker Log : v0.5 ][ -- flight online --] [ -- Recorded Flight Time: $flighttime -- ][ -- End Log -- ]";


                  self::filepirep($pilotid, $code, $flightnumber, $routeid, $bidid, $departureicao, $arrivalicao, $route, $aircraft, $load, $flighttime, $landingrate, $comments, $fuelused, $log);
                  self::resetOnlineFlights_post_PIREP($flightdata->id);
                  }
                }
              }
              }
            }
          }

          echo "<br>END FLIGHT CHECK";
        }


        public static function checkOnlineFlightsOnDB_VATSIM($online_flights = 0) {
          $sql = "SELECT * FROM `icrew_tracker_currentflights` WHERE `network` = 'VATSIM'";
          $result = DB::get_results($sql);

          if($result != '') {
            echo "<br>Checking icrew_tracker_currentflights table (VATSIM)....<br>";
            foreach ($result as $flight) {
              echo $flight->callsign;

              //if flight is live

              if (in_array($flight->callsign, $online_flights)) {
                echo " - Flight found online! No need to file PIREP.<br>";

              } else {
                echo " - Flight not found ONLINE, must have ended....filing PIREP<br>";
                DiscordData::deliver("@everyone Filing PIREP for $flight->callsign through cron!");
                $flightdata = self::getOnlineFlightData($flight->callsign);
                foreach ($flightdata as $flightdata) {
                echo "Flight Bid ID (check if bid is there on phpvms_bids) : ".$flightdata->bidid."<br>";
                if($flightdata == '') {
                  DiscordData::deliver("@everyone ERROR in Filing PIREP for $flight->callsign, no data found in `icrew_tracker_currentflights`");
                } else {
                  //Get Schedule Data

                  $bid = SchedulesData::getBid($flightdata->bidid);
                  if($bid == '') {
                    echo "ERROR: BID NOT FOUND! Unable to file PIREP <br>";
                  } else {
                      echo "Bid found! <br> ";

                  $schedules = SchedulesData::getSchedule($bid->routeid);
                  $pilotid = $flightdata->pilotid;
                  $aircraft = $schedules->aircraftid;
                  $code = $schedules->code;
                  $flightnumber = $schedules->flightnum;
                  $routeid = $schedules->routeid;
                  $bidid = $flightdata->bidid;
                  $departureicao = $schedules->depicao;
                  $arrivalicao = $schedules->arricao;
                  $route = $flightdata->route;
                  $load = "250"; // RANDOM
                  $flighttime = $flightdata->online_time;
                  $landingrate = "0";
                  $comments = "iCrewTrackerPRO VATSIM Test Flight.";
                  $fuelused = "2000"; // RANDOM
                  $log = "iCrewTracker Log : v0.1 ][ -- flight online --] [ -- Recorded Flight Time: $flighttime -- ][ -- End Log -- ]";


                  self::filepirep($pilotid, $code, $flightnumber, $routeid, $bidid, $departureicao, $arrivalicao, $route, $aircraft, $load, $flighttime, $landingrate, $comments, $fuelused, $log);
                  self::resetOnlineFlights_post_PIREP($flightdata->id);
                  }
                }
              }
              }
            }
          }

          echo "<br>END FLIGHT CHECK";
        }




  }
