<?php


class CodeShare_admin extends CodonModule
{
    public function HTMLHead()
    {
        $this->set('sidebar', 'codeshare/sidebar_codeshare.php');
    }

    public function NavBar()
    {
        echo '<li><a href="'.SITE_URL.'/admin/index.php/codeshare_admin">Codeshares</a></li>';
    }

    public function index()
    {
        if($this->post->action == 'save_new_codeshare')
        {
            $this->save_new_codeshare();
        }
        elseif($this->post->action == 'save_edit_codeshare')
        {
            $this->save_edit_codeshare();
        }
        else
        {
            // $this->set('codeshare', CodeShareData::get_upcoming_codeshares());
			      // $this->set('history', CodeShareData::get_past_codeshare());
            //
            $this->set('airlines', CodeShareData::getCodeShare_airlines());
            $this->show('codeshare/codeshare_index.php');
        }
    }

    public function viewairline($icao) {

      $this->set('codeshare', CodeShareData::check_airline($icao));
      $this->set('schedules', CodeShareData::get_codeshares_icao($icao));
      $this->show('codeshare/view_airline.php');
    }
    public function newairline() {
      $this->set('title', 'New CodeShare airline');
      $this->show('codeshare/codeshare_header.php');
      $this->show('codeshare/newairline_form.php');
    }

    public function import() {

      $this->set('title', 'Import CodeShare Schedules from CSV file!');
      $this->show('codeshare/codeshare_header.php');
      $this->show('codeshare/import.php');

    }

    public function addcodeshare() {
      $this->set('title', 'Manually add CodeShare Schedules!');
      $this->show('codeshare/codeshare_header.php');
      $this->set('allairlines', CodeShareData::getCodeShare_airlines());
      $this->set('allaircraft', OperationsData::GetAllAircraft());
      $this->set('allairports', OperationsData::GetAllAirports());
      //$this->set('airport_json_list', OperationsData::getAllAirportsJSON());
      $this->set('flighttypes', Config::Get('FLIGHT_TYPES'));
      $this->show('codeshare/add_form.php');
    }

    public function add_flight() {

      if($_POST && $_POST['submit'] == 'Add Flight') {
        $this->checkPermission(EDIT_SCHEDULES);

        $gen = CodeShareData::CodeShareFlightNum($this->post->flightnum);
        $code = CODESHARE_MAIN_AIRLINE;
        $flightnum = $gen['flightnum'];


        if ($this->post->code == '' || $this->post->flightnum == '' || $this->post->deptime ==
            '' || $this->post->arrtime == '' || $this->post->depicao == '' || $this->post->arricao ==
            '') {
            $this->set('message', 'All of the fields must be filled out');
            $this->render('core_error.php');
            $this->addcodeshare();
            return;
        }

        # Check if the schedule exists
        $sched = SchedulesData::getScheduleByFlight($code, $flightnum);
        if (is_object($sched)) {
            $this->set('message', 'Ooops, a CodeShare with this flight number "'.$code.''.$flightnum.'" already exists in the Schedule Database!');
            $this->render('core_error.php');

            return;
        }

        $enabled = ($this->post->enabled == 'on') ? true : false;

        # Check the distance
        if ($this->post->distance == '' || $this->post->distance == 0) {
            $this->post->distance = OperationsData::getAirportDistance($this->post->depicao,
                $this->post->arricao);
        }

        # Format the flight level
        $this->post->flightlevel = str_replace(',', '', $this->post->flightlevel);
        $this->post->flightlevel = str_replace(' ', '', $this->post->flightlevel);

        $this->post->route = strtoupper($this->post->route);
        $this->post->route = str_replace($this->post->depicao, '', $this->post->route);
        $this->post->route = str_replace($this->post->arricao, '', $this->post->route);
        $this->post->route = str_replace('SID', '', $this->post->route);
        $this->post->route = str_replace('STAR', '', $this->post->route);

        if(is_array($_POST['daysofweek'])) {
            $daysofweek = implode('', $_POST['daysofweek']);
        } else {
            $daysofweek = '0123456'; # default activate for all days
        }

        if (is_array($_POST['week1'])) {
            $week1 = implode('', $_POST['week1']);
        } else {
            $week1 = '';
        }

        if (is_array($_POST['week2'])) {
            $week2 = implode('', $_POST['week2']);
        } else {
            $week2 = '';
        }

        if (is_array($_POST['week3'])) {
            $week3 = implode('', $_POST['week3']);
        } else {
            $week3 = '';
        }

        if (is_array($_POST['week4'])) {
            $week4 = implode('', $_POST['week4']);
        } else {
            $week4 = '';
        }





        $data = array(
            'code' => $code,
            'flightnum' => $flightnum,
            'depicao' => $this->post->depicao,
            'arricao' => $this->post->arricao,
            'route' => $this->post->route,
            'aircraft' => $this->post->aircraft,
            'flightlevel' => $this->post->flightlevel,
            'distance' => $this->post->distance,
            'deptime' => $this->post->deptime,
            'arrtime' => $this->post->arrtime,
            'flighttime' => $this->post->flighttime,
            'daysofweek' => $daysofweek,
            'week1' => $week1, 'week2' => $week2, 'week3' => $week3, 'week4' => $week4,
            'price' => $this->post->price,
            'payforflight' => $this->post->payforflight,
            'flighttype' => $this->post->flighttype,
            'notes' => $this->post->notes,
            'enabled' => $enabled
        );

        # Add it in
        $ret = SchedulesData::AddSchedule($data);

        $get_sch = SchedulesData::findFlight($flightnum);
        $operator = $this->post->code;
        CodeShareData::save_new_codeshare($get_sch->id, $code, $operator);


        if (DB::errno() != 0 && $ret == false) {
            $this->set('message',
                'There was an error adding the schedule, already exists DB error: ' . DB::error
                ());
            $this->render('core_error.php');
            return;
        }

        $this->set('message', 'The schedule "' .$code . $flightnum .
            '" has been added');
        $this->render('core_success.php');


		$name = Auth::$userinfo->firstname.' added a new CodeShare Schedule,  '.$code .$flightnum.' from '.$this->post->depicao.' - '.$this->post->arricao.' to our routes database! #weareexpanding';
        $posted_by = 'Admin Bot';
        $privacy = '0';
        ICSActs::new_ics_activity($name, $posted_by, $privacy);

        LogData::addLog(Auth::$userinfo->pilotid, 'Added CodeShare Schedule manually "' .$code . $flightnum . '"');

      }

    }
    public function processimport() {
        $this->checkPermission(IMPORT_SCHEDULES);
        $this->show('codeshare/codeshare_header.php');
        echo '<h3>Processing Import</h3>';

        if (!file_exists($_FILES['uploadedfile']['tmp_name'])) {
            $this->set('message', 'File upload failed!');
            $this->render('core_error.php');
            return;
        }

        echo '<p><strong>DO NOT REFRESH OR STOP THIS PAGE</strong></p>';

        set_time_limit(270);
        $errs = array();
        $skip = false;


        # Fix for bug VMS-325
        $temp_name = $_FILES['uploadedfile']['tmp_name'];
        $new_name = CACHE_PATH . $_FILES['uploadedfile']['name'];
        move_uploaded_file($temp_name, $new_name);

        $fp = fopen($new_name, 'r');

        if (isset($_POST['header']))
            $skip = true;

        /* Delete all schedules before doing an import */
        if (isset($_POST['erase_routes'])) {
            SchedulesData::deleteAllSchedules();
        }


        $added = 0;
        $updated = 0;
        $total = 0;
        echo '<div style="overflow: auto; height: 400px; border: 0px solid #666; margin-bottom: 20px; padding: 5px; padding-top: 0px; padding-bottom: 20px;">';

        while ($fields = fgetcsv($fp, 1000, ',')) {
            // Skip the first line
            if ($skip == true) {
                $skip = false;
                continue;
            }

            // list fields:
            $code = $fields[0];
            $flightnum = $fields[1];
            $depicao = $fields[2];
            $arricao = $fields[3];
            $route = $fields[4];
            $aircraft = $fields[5];
            $flightlevel = $fields[6];
            $distance = $fields[7];
            $deptime = $fields[8];
            $arrtime = $fields[9];
            $flighttime = $fields[10];
            $notes = $fields[11];
            $price = $fields[12];
            $flighttype = $fields[13];
            $daysofweek = $fields[14];
            $enabled = $fields[15];
            $week1 = $fields[16];
            $week2 = $fields[17];
            $week3 = $fields[18];
            $week4 = $fields[19];

            if ($code == '') {
                continue;
            }



            // Check the code:
            $check = CodeShareData::check_airline($code);
            if (!$check) {
                echo "$code - CodeShare airline not found, Skipping...<br />";
                continue;
            }

            // Make sure airports exist:
            if (!($depapt = OperationsData::GetAirportInfo($depicao))) {
                $this->get_airport_info($depicao);
            }

            if (!($arrapt = OperationsData::GetAirportInfo($arricao))) {
                $this->get_airport_info($arricao);
            }

            # Check the aircraft
            $aircraft = trim($aircraft);
            $ac_info = OperationsData::GetAircraftByReg($aircraft);

            # If the aircraft doesn't exist, skip it
            if (!$ac_info) {
                echo 'Aircraft "' . $aircraft . '" does not exist! Skipping<br />';
                continue;
            }
            $ac = $ac_info->id;

            if ($flighttype == '') {
                $flighttype = 'P';
            }

            if ($daysofweek == '')
                $daysofweek = '0123456';

            // Replace a 7 (Sunday) with 0 (since PHP thinks 0 is Sunday)
            $daysofweek = str_replace('7', '0', $daysofweek);

            # Check the distance

            if ($distance == 0 || $distance == '') {
                $distance = OperationsData::getAirportDistance($depicao, $arricao);
            }

            $flighttype = strtoupper($flighttype);

            if ($enabled == '0')
                $enabled = false;
            else
                $enabled = true;

            # This is our 'struct' we're passing into the schedule function
            #	to add or edit it

            $gen = CodeShareData::CodeShareFlightNum($flightnum);
            $codeshare_airline = CODESHARE_MAIN_AIRLINE;
            $codeshare_flightnum = $gen['flightnum'];
            $notes .= $gen['notes'];

            $data = array(
                'code' => $codeshare_airline, 'flightnum' => $codeshare_flightnum, 'depicao' => $depicao,
                'arricao' => $arricao, 'route' => $route, 'aircraft' => $ac, 'flightlevel' => $flightlevel,
                'distance' => $distance, 'deptime' => $deptime, 'arrtime' => $arrtime,
                'flighttime' => $flighttime, 'daysofweek' => $daysofweek, 'notes' => $notes,
                'enabled' => $enabled, 'price' => $price, 'flighttype' => $flighttype,
                'week1' => $week1, 'week2' => $week2, 'week3' => $week3, 'week4' => $week4
            );

            # Check if the schedule exists:
            if (($schedinfo = SchedulesData::getScheduleByFlight($codeshare_airline, $codeshare_flightnum))) {
                # Update the schedule instead
                $val = SchedulesData::updateScheduleFields($schedinfo->id, $data);
                $get_sch = SchedulesData::findFlight($codeshare_flightnum);
                CodeShareData::updateCodeShareflight($schedinfo->id, $codeshare_airline);
                $updated++;
            } else {
                # Add it

                $val = SchedulesData::addSchedule($data);
                $get_sch = SchedulesData::findFlight($codeshare_flightnum);
                CodeShareData::save_new_codeshare($get_sch->id, $codeshare_airline);
                $added++;
            }

            if ($val === false) {
                if (DB::errno() == 1216) {
                    echo "Error adding $code$flightnum: The airline code, airports, or aircraft does not exist";
                } else {
                    $error = (DB::error() != '') ? DB::error() : 'Route already exists';
                    echo "$code$flightnum was not added, reason: $error<br />";
                }

                echo '<br />';
            } else {
                $total++;


                echo "CodeShare {$code}{$flightnum} ({$depicao} to {$arricao}) added as <strong>{$codeshare_airline}{$codeshare_flightnum}</strong> <br />";

            }
        }

        CentralData::send_schedules();

        echo "<hr> <div class='alert alert-info'>The Codeshare import process is complete, added {$added} CodeShare schedules, updated {$updated}, for a total of {$total}<br /> Happy CodeSharing!</div>";
        foreach ($errs as $error) {
            echo '&nbsp;&nbsp;&nbsp;&nbsp;' . $error . '<br />';
        }

        echo '</div>';

        unlink($new_name);
    }

    public function addnewairline() {


      $airlinename = $this->post->airline_name;
      $icao = $this->post->icao;
      $status = $this->post->status;


      $logo = $_FILES['logo']['name'];
      $logo_name = strtoupper($icao);
			$logo_name = str_replace(' ', '_', $logo_name);
			$logo_name = $logo_name.'.png';
			$logo_path = "../codeshare_logos/".$logo_name;
			move_uploaded_file($_FILES["logo"]["tmp_name"],$logo_path);

      $logo = SITE_URL."/codeshare_logos/".$logo_name;
      $check = CodeShareData::check_airline($icao);

      if(count($check) > 0) {
        $this->set('message', '<strong>Oops</strong><br> An airline with this ICAO code "'.$icao.'" already exists!');
        $this->show('core_error.php');
        $this->newairline();
        return;
      } else {
        $add = CodeShareData::add_newairline($airlinename, $icao, $logo, $status);
        if($add) {
          $this->set('message', '<strong>Success</strong> <br> New Codeshare airline '.$airlinename.' added!');
          $this->show('core_success.php');
        } else {
          $this->set('message', '<strong>Oops</strong><br> There was a problem in adding the CodeShare airline!');
          $this->show('core_error.php');
        }

        $this->index();
      }



    }


    public function editairline($id) {
      $this->set('codeshare', CodeShareData::get_airline($id));
      $this->show('codeshare/codeshares_codeshare.php');

    }

    public function editairline_save($id) {
      $airlinename = $this->post->airline_name;
      $icao = $this->post->icao;
      $status = $this->post->status;

      $logo = $_FILES['logo']['name'];
      $logo_name = strtoupper($icao);
			$logo_name = str_replace(' ', '_', $logo_name);
			$logo_name = $logo_name.'.png';
			$logo_path = "../codeshare_logos/".$logo_name;
			move_uploaded_file($_FILES["logo"]["tmp_name"],$logo_path);

      $logo = SITE_URL."/codeshare_logos/".$logo_name;
      $add = CodeShareData::edit_airline($id, $icao, $logo, $airlinename, $status);
      $this->set('message', '<strong>Success</strong> <br> '.$airlinename.' was saved!');
      $this->show('core_success.php');

      $this->index();
    }


    public function get_codeshares()
    {
        $id = $_GET[id];
        $this->set('codeshare', CodeShareData::get_codeshares($id));

        $this->show('codeshare/codeshares_codeshare.php');
    }
    public function new_codeshare()
    {
        $this->show('codeshare/codeshare_new_form.php');
    }
    protected function save_new_codeshare()
    {
        $codeshare = array();

        $codeshare['schedid'] = DB::escape($this->post->schedid);
        $codeshare['airline'] = DB::escape($this->post->airline);
		    $codeshare['image'] = DB::escape($this->post->image);



        foreach($codeshare as $test)
        {
            if(empty($test))
            {
                $this->set('codeshare', $codeshare);
                $this->show('codeshare/codeshare_new_form.php');
                return;
            }
        }



        CodeShareData::save_new_codeshare($codeshare['schedid'], $codeshare['airline'], $codeshare['image']);




        $this->set('codeshare', CodeShareData::get_upcoming_codeshares());

        $this->show('codeshare/codeshare_index.php');
    }
    public function edit_codeshare() {
            $id = $_GET[id];
            $codeshare = array();
            $codeshare = CodeShareData::get_codeshares($id);
            $this->set('codeshare', $codeshare);
            $this->show('codeshare/codeshare_edit_form.php');
    }
    protected function save_edit_codeshare()
    {
        $codeshare = array();

        $codeshare['schedid'] = DB::escape($this->post->schedid);
        $codeshare['airline'] = DB::escape($this->post->airline);
		$codeshare['image'] = DB::escape($this->post->image);
		$codeshare['id'] = DB::escape($this->post->id);


        CodeShareData::save_edit_codeshare($codeshare['schedid'],
										   $codeshare['airline'],
										   $codeshare['image'],
										   $codeshare['id']);

        $id = $codeshare['id'];
        $this->set('codeshare', CodeShareData::get_codeshares($id));

        $this->show('codeshare/codeshares_codeshare.php');
    }

    public function delete_codeshare()
    {
        $id = $_GET[id];
        CodeShareData::delete_codeshare($id);

        $this->set('codeshare', CodeShareData::get_upcoming_codeshares());
        $this->show('codeshare/codeshare_index.php');
    }
}
