<?php
// Config values

$ivao_field_id_in_phpVMS_db = 2;
$match_case = "ICREWTRACKER";

// Download the files

$file_name_ivao = SITE_ROOT . "iCrewTracker-IVAOData.txt";



if (!file_exists($file_name_ivao) || time() - filemtime($file_name_ivao) > 300) {
    iCrewTrackerData::downloadIVAOAPIData($file_name_ivao);
} else if ($_GET['action'] == 'force_download') {
    echo "Initiating FORCE Download...<br>";
    iCrewTrackerData::downloadIVAOAPIData($file_name_ivao);

} else {
    echo "Latest API data exists. " . $file_name_ivao . "," . filesize($file_name_ivao) . " bytes";
    echo "<br>";
    echo "<a href='?action=force_download' class='btn btn-success'>Force Download</a>";
}



// Parse it
//
// $countryicao = 'VO';
// // Put here country code of staff members
// $staffcountry = 'in';
// $airports = array(
//    'VOMF' => 'Example Area Sector',
// 'VOMM' => 'Example Airport',
// );

$lng['trafficingb'] = 'Pilots';
$lng['notrafficingb'] = 'There is no traffic in the specified Airspace';


$validcontrollers = array('DEL','GND','TWR','DEP','APP','CTR','FSS');
$service = array(
'DEL' => 'Delivery',
'GND' => 'Ground',
'TWR' => 'Tower',
'APP' => 'Radar',
'DEP' => 'APP / Radar',
'CTR' => 'Sector',
'FSS' => '',
);
$ctrlevel = array(
  1 => 'OBS',
  2 => 'AS1',
  3 => 'AS2',
  4 => 'AS3',
  5 => 'ADC',
  6 => 'APC',
  7 => 'ACC',
  8 => '<span class="green">SEC</span>',
  9 => '<span class="green">SAI</span>',
 10 => '<span class="green">CAI</span>',
 11 => '<span class="red">SUP</span>',
 12 => '<span class="red">ADM</span>'
);


$filecontents = file_get_contents($file_name_ivao); //Testing file

$rows            = explode("\n", $filecontents);
$filepart        = '';
$pilots          = array();
$pilotcount      = 0;
$controllers     = array();
$staff           = array();
$controllercount = 0;
$generaldata     = array();
$rating          = $pilot[41];
foreach ($rows as $row) {
    if (substr($row, 0, 1) == '!') {
        $filepart = substr($row, 1);
    } else {
        switch ($filepart) {
            case 'CLIENTS':
                $fields = explode(":", $row);
                if ($fields[3] == 'ATC') {
                    $controllercount++;
                    if (in_array(substr($fields[0], -3), $validcontrollers) && substr($fields[0], 0, strlen($countryicao)) == $countryicao) {
                        array_push($controllers, $fields);
                    }
                    if (substr($fields[0], 0, 3) == $staffcountry . '-') {
                        array_push($staff, $fields);
                    }
                } else {
                    $pilotcount++;
                    if (substr($fields[11], 0, strlen($countryicao)) == $countryicao OR substr($fields[13], 0, strlen($countryicao)) == $countryicao) {
                        $countrypcount++;
                        //if ($countrypcount <= 20) {
                        array_push($pilots, $fields);
                        //}
                    }
                }
                break;
            case 'GENERAL':
                list($key, $value) = explode('=', $row);
                $generaldata[trim($key)] = trim($value);
                break;
        }
    }
}
// ATC
//-------------------------------------------------------------------------------------------------------------------//
// Check there is ATC online then show count
//echo '<h3 align="left">' . $lng['atcingb'] ;
//if(count($controllers) != 0) echo ' ('.count($controllers).')';
//echo '</h3>';
//echo "<img src= "<?php echo $rating "";



if (count($pilots) != 0) {

    ?>

    <div class="row">
      <div class="col-md-12">
        <div class="block">
          Path for CronJob :
          <br>
          <code> */5 * * * *	/usr/bin/wget --spider "<?php echo SITE_URL."/action.php/iCrewTracker/cron_call"; ?>"</code>
          <br><br>
        </div>

      </div>
      <div class="col-md-12">
        <div class="block">
          <div class="block-title">
            <h3>Online Flights on IVAO, <?php echo $lng['trafficingb'] . ' (' . count($pilots) . ')'; ?></h3>
          </div>
          <div class="table-responsive">
          <?php
            // $string = "AAL132:811045:John Bradley KDFW:PILOT::28.06200:-82.80799:39241:547:H/B772/L:474:KORD:39000:KMIA:USA-WEST:100:1:3165:::7:I:2045:2045:2:22:4:7:KMCO:+VFPS+/T/WWW.JOINAVA.ORG/DFW SIMBRIEF:DENNT1/28R ORD5 DENNT DARCY DREGS DUMGE SCOTO SWAPP ATL SZW PLYER JUULI:0:0:0:0:::20191121202836:154:30.16:1021:";
            // $display = explode(":", $string); $i = 0; foreach ($display as $dis) { echo $i."). ".$dis; echo "<br>"; $i++; }

            // $sql = "INSERT INTO {$dbprefix}IVAOData
            //  (Callsign, VID, Name,
            //   Lat, Lon, Alt,
            //   GS, AC, FiledSpd,
            //   DepICAO, FiledAlt, DesICAO,
            //   FlightRules, DepTime, ETE,
            //   AltICAO, Remarks, Route,
            //   FlightType, HDG, OnGND,
            //   Network)
            //
            //   $tarr[0]', $tarr[1], '$tarr[2]',
            //   $tarr[5], $tarr[6], $tarr[7],
            //   $tarr[8], '$tarr[9]', '$tarr[10]',
            //   $tarr[11]', '$tarr[12]', '$tarr[13]',
            //   $tarr[21]', '$deptime', '$ete',
            //   $tarr[28]', '$tarr[29]', '$tarr[30]',
            //   $tarr[43]', $tarr[45], $tarr[46],
            //     $networkid"";
            //



            ?>
          <table class="table table-hover table-responsive">
            <thead>
              <th>Flight #</th>
              <th>DEP - ARR</th>
              <th>A/C</th>
              <th>VID</th>
              <th>NAME</th>
              <th>ALT</th>
              <th>HDG</th>
              <th>SPEED</th>
              <th>STATUS</th>
              <th>TOTAL DISTANCE</th>
              <th>COVERED DISTANCE</th>
              <th>REMAINING DISTANCE</th>
              <th>REMAINING TIME</th>
              <th>ONLINE TIME</th>
              <th>OPTIONS</th>
            </thead>


            <?php
              foreach ($pilots as $pilot) {
                $check = iCrewTrackerData::checkPilot_IVAO($pilot[1], $ivao_field_id_in_phpVMS_db);
                if($check == 1) {
                if($count > 10) { continue; } ?>


                <?php
                $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
                }
                ?>
                  <tr>
                    <?php
                      // foreach ($pilot as $pDisplayData) {  echo "<td>". $pDisplayData ."</td>"; }
                    ?>
                    <td><?php echo $pilot[0]; ?></td>
                    <td><?php echo $pilot[11] ?> <i class="fa fa-plane"></i> <?php echo $pilot[13]; ?></td>
                    <td><?php
                      $ac = $pilot[9];
                      $ac = explode("/", $ac);
                      $aircraft = $ac[1];
                     ?></td>
                    <td><a href="https://www.ivao.aero/Member.aspx?Id=<?php echo $pilot[1]; ?>" target="_blank"><?php echo $pilot[1]; ?></a></td>
                    <td><?php
                    $pilotdata = iCrewTrackerData::getPilotData_IVAO($pilot[1], $ivao_field_id_in_phpVMS_db);
                    echo $pilotdata->code.$pilotdata->pilotid.' '. $pilotdata->firstname.' '.$pilotdata->lastname;
                     ?></td>
                    <td><?php echo $pilot[7]; ?> ft</td>
                    <td><?php echo $pilot[45]; ?>&deg;</td>
                    <td><?php echo $pilot[8]; ?> Kts</td>
                    <td>STATUS</td>
                    <td>
                      <?php
                      $total_distance = OperationsData::getAirportDistance($pilot[11], $pilot[13]);
                        echo round($total_distance);
                      ?> nm <i class="fa fa-check"></i>
                    </td>
                    <td><?php
                        //Covered Distance

                        $filed_speed = $pilot[10];
                        $filed_speed = preg_replace("/[^0-9]/", "", $filed_speed);
                        echo $filed_speed ."KIAS ";

                        $ts1 = strtotime($pilot[37]);
                        $ts2 = strtotime(date('YmdHis'));
                        $time_difference = $ts2 - $ts1;

                        $time = round($time_difference / 60); // In minutes
                        $timxe = iCrewTrackerData::calculateOnlineTime($pilot[37]);
                        echo "time : ";
                        print_r($timxe);
                        echo "<br>";
                        $covered_dist = $filed_speed * ($time / 60);
                        echo $covered_dist;
                        ?> nm
                    </td>
                    <td>
                      <?php
                      $distance_2_go = $total_distance - $covered_dist;
                      echo round($distance_2_go);
                      ?> nm
                    </td>

                    <td>
                      <?php
                        // Time to Go
                        $time = ($distance_2_go / $pilot[8]) * 60;
                        $time_2_go = date('H:i', mktime(0,$time));
                        echo $time_2_go;
                      ?>

                    </td>
                    <td><?php echo iCrewTrackerData::calculateOnlineTime($pilot[37])['formatted_time']; ?></td>
                    <td><a href="#" class="btn btn-xs btn-success">TRACK</a>
                      <button type="button" class="btn btn-xs btn-primary" data-container="body" data-toggle="popover" data-placement="top"
                       data-content="FP REMARKS: <?php echo $pilot[29]; ?>">
                        FP REMARK
                      </button>
                      <!-- Button trigger modal -->
                      <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#<?php echo $pilot[1]; ?>">
                        DETAILS
                      </button>

                        <!-- Modal -->
                          <div class="modal fade" id="<?php echo $pilot[1]; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                              <div class="modal-content">
                                <div class="modal-header">
                                  <h3 class="modal-title"><?php echo $pilot[0]; ?> Flight Details</h3>
                                </div>
                                <div class="modal-body">
                                  <?php

                                  // Verify if bid exists

                                  $sql = "SELECT * FROM ".TABLE_PREFIX."bids WHERE `pilotid` = '$pilotdata->pilotid'";
                                  $bids_from_db = DB::get_results($sql);

                                  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;
                                    print_r($schedules);
                                    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` (`id`, `callsign`, `pilotid`, `network_id`, `network`, `status`) VALUES (NULL, $pilot[0], $pilotdata->pilotid, $pilot[1], 'IVAO', 'UNDEFINED')";
                                        DB::query($sql);
                                        echo "Entry for ".$pilot[0]." made into `icrew_tracker_currentflights` table!";

                                      } else {
                                        // ENtry already present. Continue with updating other table data
                                        echo "Entry for $pilot[0] was already made, populating other tables";

                                        // Make entry into ACARSData tables
                                        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");

                                      }

                                    } else {
                                      echo $sch_callsign. " Callsigns donot match";
                                    }
                                  }
                                } else {
                                  echo "No bids found for ".$pilot[0];
                                }

                                  // Check if entry has been made to the icrew_tracker_currentflights table

                                  // Check if entry is being made to the phpvms_acarsdata table

                                  // Check if entry is being made to the acars_data table.



                                  ?>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    <button type="button" class="btn btn-primary">Save changes</button>
                                </div>
                              </div>
                            </div>
                          </div>

                    </td>
                  </tr>
                <?php
                $count++;
              }
            }
          ?>



      </table>
    </div>
    </div>
  </div>
  </div>
<?php } else {
  "No flights for the selected VID";
}



// FInd a specific VID / CID

// GEt data from that VID

// Log that into the DB

// File PIREP based on that
?>
