<?php
require_once('../classes/api.php');

/**
 * Class GetFlightInfo
 * Get flight details
 */
class GetFlightInfo extends APIPage
{
   public function __construct()
   {
      // we want db connection
      parent::__construct(true);
   }

   public function render($regex_matches)
   {

      // Get flight id
      $flight_id = $regex_matches[1];

      // Call db to get rows
      $this->output = $this->db->getFlight($flight_id);

      // Find the julian date from unix time from db time. Adds one to julian day as PHPs julian day is 0 based
      $unixSeconds                = strtotime($this->output['flight_date']);
      $this->output['year']       = date('Y', $unixSeconds);
      $this->output['julian_day'] = date('z', $unixSeconds) + 1;
   }
}

/**
 * Class UpdateFlight
 * Update flight details
 */
class UpdateFlight extends APIPage
{
   public function __construct()
   {
      // we want db connection
      parent::__construct(true);
   }

   public function render($regex_matches)
   {

      // Get flight id
      $flight_id = $regex_matches[1];

      // Gets "post" variables from data that is in the format of a query string
      parse_str(file_get_contents("php://input"), $post_vars);
      $needed_keys = array('flight_year', 'flight_day', 'flight_letter',
           'flight_area', 'flight_primary_ticket', 'flight_secondary_ticket',
           'flight_kml', 'flight_notes', 'flight_datalocation');


      if($this->has_keys($post_vars, $needed_keys) == false) {
         // Error, Not enough keys
         $this->error('Incorrect number of parameters sent to the api.');
      } else {
         // Validation success

         // Create date for database based on year and julian day
         $date = DateTime::createFromFormat('z Y', ($post_vars['flight_day'] - 1) . ' ' . $post_vars['flight_year'])->format('Y-m-d');

         // Format the secondary tickets array.
         $secondary_tickets = '{' . str_replace(' ', ',', $post_vars['flight_secondary_ticket']) . '}';

         // Form array of parameters to sent to db
         $parameter_array = array($flight_id, $date,
              $post_vars['flight_primary_ticket'], $post_vars['flight_kml'],
              $post_vars['flight_datalocation'], $post_vars['flight_letter'],
              $post_vars['flight_notes'], $secondary_tickets,
              $post_vars['flight_area'], $post_vars['flight_priority']);

         // Send to database
         $database_update_result = $this->db->update_flight($parameter_array);
         if($database_update_result) {
            // Success
            $this->output['success'] = true;
         } else {
            // Database Error
            $this->error('Failed to insert into the database.');
         }
      }
   }
}

/**
 * Class DeleteFlight
 * Delete flight
 */
class DeleteFlight extends APIPage
{
   public function __construct()
   {
      // we want db connection
      parent::__construct(true);
   }

   public function render($regex_matches)
   {

      // Get flight id
      $flight_id = $regex_matches[1];

      // Call db to delete row
      $database_delete_result = $this->db->delete_flight($flight_id);

      if($database_delete_result) {
         // Success
         $this->output['success'] = true;
      } else {
         // Database Error
         $this->error('Failed to delete from the database.');
      }
   }
}

/**
 * Class GetProgressFlightInfo
 */
class GetProgressFlightInfo extends APIPage
{
   public function __construct()
   {
      // we want db connection
      parent::__construct(true);
   }

   public function render($regex_matches)
   {

      // Get flight id
      $flight_id = $regex_matches[1];

      // Call db to get rows
      $this->output = $this->db->getProgressPageFlight($flight_id);

      // Find the julian date from unix time from db time. Adds one to julian day as PHPs julian day is 0 based
      $unixSeconds                = strtotime($this->output['flight_date']);
      $this->output['year']       = date('Y', $unixSeconds);
      $this->output['julian_day'] = date('z', $unixSeconds) + 1;
   }
}

/**
 * Class InsertFlight
 * Add new flight to database
 */
class InsertFlight extends APIPage
{
   public function __construct()
   {
      // we want db connection
      parent::__construct(true);
   }

   public function render($regex_matches)
   {

      // Get flight id
      //$flight_id = $regex_matches[1];

      // Decode the posted json
      $post_json = json_decode(file_get_contents("php://input"));

      $date          = DateTime::createFromFormat('z Y', ($post_json->flight_day - 1) . ' ' . $post_json->flight_year)->format('Y-m-d');
      $data_location = $post_json->data_location;
      if($data_location == "") {
         $data_location = null;
      }

      $date_recieved = $post_json->date_recieved;
      if($date_recieved == "") {
         $date_recieved = null;
      } else {
         $date_recieved = DateTime::createFromFormat('j/m/Y', $date_recieved)->format('Y-m-d');
      }

      $notes = $post_json->flight_notes;
      if($notes == "") {
         $notes = null;
      }

      $flight_array = array($date, $post_json->flight_letter, $post_json->flight_area, $post_json->flight_priority, $notes, $date_recieved, $data_location);

      $project_array = $post_json->projects;
      $sensor_array  = array();

      foreach($post_json->sensors as $sensor) {
         $sensor_array[] = array($sensor->sensor, $sensor->no_of_lines, $sensor->priority);
      }


      // Call db to get rows
      $database_insert_result = $this->db->insert_flight($flight_array, $project_array, $sensor_array);
      if($database_insert_result) {
         // Success
         $this->output['success'] = true;
      } else {
         // Database Error
         $this->error('Failed to insert into the database.');
      }

   }
}
