<center>
  <img src="https://cdn.discordapp.com/attachments/530789778912837640/647205933348421632/1574375698436.png" width="auto;" height="250px;" />
  <br>
  <p>Who said you need an ACARS Software to track your flights?</p>
  <h1>VATSIM Tracker</h1>
</center>
  <?php
  //If you need to debug, or find out why you can't send message uncomment line below, and execute script.
  //echo $response;


    $file_name_ivao = SITE_ROOT . "iCrewTrackerData-VATSIMData.txt";
    $vatsim_field_id_in_phpVMS_db = 1; // 1 for VATSIM, 2 for IVAO;
    $match_case = "RMK/ICREWTRACKER TEST";


    // Downloading the Data
    if (!file_exists($file_name_ivao) || time() - filemtime($file_name_ivao) > 300) {
      iCrewTrackerData::downloadVATSIMAPIData($file_name_ivao);
      echo "Data downloaded...<br>";
    } else if ($_GET['action'] == 'force_download') {
      iCrewTrackerData::downloadVATSIMAPIData($file_name_ivao);
      echo "Data downloaded...<br>";
    } else {
      echo "Latest Data found...<br>";
    }


    $filecontents = file_get_contents($file_name_ivao);
    echo "Parsing Data...<br>";
    $rows            = explode("\n", $filecontents);
    $filepart        = '';
    $pilots          = array();
    $pilotcount      = 0;
    $controllers     = array();
    $staff           = array();
    $controllercount = 0;
    $generaldata     = array();
    $rating          = $pilot[41];

    $onliecount = 0;
    foreach ($rows as $row) {
      if($onlinecount > 50) {
        continue;
      } else {

        $split = str_split($row);


        if($fileHasBegin == 1) {
          $fields = explode(":", $row);
          array_push($pilots, $fields);
        } else {
          if($split[0] == "!" && $split[1] == "C") {
            $fileHasBegin = 1;
            echo $row;
            echo "READING ALL DATA BELOW<br>";
            echo "<hr>";
          }
        }











      }
    }

// If there are more than 0 pilots online on IVAO
if (count($pilots) != 0) {
            echo "Displaying pilot data...<br>";
            echo count($pilots)." online connections found....<br>";
            $online_flights = array();
              foreach ($pilots as $pilot) {
                $check = iCrewTrackerData::checkPilot_VATSIM($pilot[1], $vatsim_field_id_in_phpVMS_db);
                if($check == 1) {
                $flightPlan_remark = $pilot[29];
                if (strpos($flightPlan_remark, $match_case) !== false) {
                  ?>
                  <span class="btn btn-danger btn-block">FP REMARK CONTAINS <?php echo $match_case; ?></span>
                  <?php
                }
                  // Parsed Data
                  echo "<br>";
                  echo $pilot[0];

                  array_push($online_flights, $pilot[0]);

                  $callsign = $pilot[0];
                  $ac = $pilot[9];
                  $ac = explode("/", $ac);
                  $aircraft = $ac[1];

                  $pilotdata = iCrewTrackerData::getPilotData_VATSIM($pilot[1], $vatsim_field_id_in_phpVMS_db);
                  $total_distance = OperationsData::getAirportDistance($pilot[11], $pilot[13]);
                  $filed_speed = $pilot[10];
                  $filed_speed = preg_replace("/[^0-9]/", "", $filed_speed);
                  // $time = calculateOnlineTime($pilot[37])['time_in_hours'];
                  $ts1 = strtotime($pilot[37]);
                  $ts2 = strtotime(date('YmdHis'));
                  $time_difference = $ts2 - $ts1;
                  $time = round($time_difference / 60); // In minutes
                  $covered_dist = $filed_speed * ($time / 60);
                  $distance_2_go = $total_distance - $covered_dist;

                  $time = ($distance_2_go / $pilot[8]) * 60;
                  $time_2_go = date('H:i', mktime(0,$time));

                  // Verify if bid exists

                  $sql = "SELECT * FROM ".TABLE_PREFIX."bids WHERE `pilotid` = '$pilotdata->pilotid'";
                  $bids_from_db = DB::get_results($sql);
                  // echo $sql;
                  // print_r($bids_from_db);
                  if($bids_from_db != '') {
                  foreach ($bids_from_db as $bid) {
                    // Check if callsign matches.
                    $schedules = SchedulesData::getSchedule($bid->routeid);
                    $sch_callsign = $schedules->code.$schedules->flightnum;
                    if($sch_callsign == $pilot[0]) {
                      echo " Callsigns match!<br>";

                      // GREEN SIGNAL Proceed to track the flights.
                      // INSERT INTO `icrew_tracker_currentflights` (`id`, `callsign`, `pilotid`, `network_id`, `network`, `status`) VALUES (NULL, 'QTR882', '107', '383376', 'IVAO', 'cruise');

                      // Check if there is an entry on ics_tck_cf table
                      $sql = "SELECT * FROM `icrew_tracker_currentflights` WHERE `callsign` = '$pilot[0]'";
                      $result = DB::get_results($sql);

                      if($result == '') {
                        // Make first entry
                        $sql = "INSERT INTO `icrew_tracker_currentflights` (`callsign`, `pilotid`, `network_id`, `network`, `status`, `bidid`) VALUES ('$pilot[0]', '$pilotdata->pilotid', '$pilot[1]', 'VATSIM', 'IN FLIGHT', '$bid->bidid')";
                        $res = DB::query($sql);
                        if($res == 1) {
                          DiscordData::deliver("$pilotdata->firstname has made a bid. Populating data on ics_tck_table for $pilot[0]");
                        } else {
                          DiscordData::deliver("BID FOUND! but unable to populate data for $pilot[0]");
                        }

                        echo "<br>";
                        echo "Entry for ".$pilot[0]." made into `icrew_tracker_currentflights` table!";

                      } else {
                        // ENtry already present. Continue with updating other table data
                        // Make entry into ACARSData tables
                        echo iCrewTrackerData::positionreport($pilotdata->pilotid, $pilot[0], $pilot[5], $pilot[6], $pilot[44], $pilot[45], $pilot[7], $pilot[8], $pilot[11], $pilot[13], $phase, $arrivaltime, $departuretime, $distance_2_go, $pilot[30], $time_2_go, $aircraft, "IVAO");
                        $flightdata = iCrewTrackerData::getOnlineFlightData($pilot[0]);
                        foreach ($flightdata as $flightdata) {
                          $id = $flightdata->id;
                        }
                        $online_time = iCrewTrackerData::calculateOnlineTime($pilot[37])['formatted_time'];
                        iCrewTrackerData::updateOnlineFlightTime($id, $online_time);
                        DiscordData::deliver("[VATSIM] Position report for $pilot[0], $time_2_go Hours remaining.");




                      }

                      // filepirep($pilotdata->pilotid, $schedules->code, $schedules->flightnum, $bid->routeid, $bid->bidid, $pilot[11], $pilot[13], $pilot[30], $schedules->aircraftid, "250", iCrewTrackerData::calculateOnlineTime($pilot[37])['formatted_time'], 0, "Tracked using iCrewTrackerPRO", "5000", "$log");

                    } else {
                      echo "- ".$sch_callsign. ". Callsigns donot match. Aborting. <br>";
                    }
                  }
                } else {
                  echo " ERROR : ".$pilotdata->firstname." ".$pilotdata->lastname." has not placed a bid for ".$pilot[0].".";
                }

                $count++;
              }
            }
          }



          iCrewTrackerData::checkOnlineFlightsOnDB_VATSIM($online_flights);
?>

<hr>
<center>
  <?php echo SITE_NAME; ?>'s iCrewTracker<strong>PRO</strong> Version 0.5 &copy; icrewsystems 2017-<?php echo date("Y"); ?>
</center>
