<?php 

/**
 * (c) 2023 iCrewTracker. All rights reserved.
 * 
 * This file is part of the iCrewTracker software suite.
 * Unauthorized copying, modification, distribution, or use of this file, 
 * via any medium, is strictly prohibited. This file is proprietary and confidential.
 * For license information, please see the LICENSE.md file.
 *
 * @author ICREWSYSTEMS SOFTWARE ENGINEERING LLP
 * @contact legal(at)icrewsystems.com 
 * @license UID cbb8060f-5d4c-45aa-8850-f4b8a87d0bcc
 * @package-bundle-hash:fe8Hghmq7t7GsZsW7KzHuTe/38L9upjcIflUqo8C5qr9iv/PeQNS
 */


namespace iCrewTracker\Controllers;

use Exception;
use iCrewTracker\Base\Config;
use iCrewTracker\Models\Pilots;
use iCrewTracker\Base\BaseController;
use Illuminate\Database\Capsule\Manager as DB;


class PilotController extends BaseController {
        

    protected $fetchable_from_model = ['firstname', 'lastname', 'code', 'pilotid', 'lastpirep', 'retired', 'confirmed', 'rank'];
    
    
    /**
     * convert_to_integer
     *
     * @param  mixed $value
     * @return void
     */
    protected function convert_to_integer($value) {
        return (!is_null($value)) ? (int) $value : $value;
    }
        
    /**
     * get_custom_fields
     *
     * @param  mixed $pilotid
     * @return void
     */
    protected function get_custom_fields(int $pilotid) {
        // Make sure that the custom fields are configured.
        $custom_fields_config = Config::get('custom_fields');

        $ivao_field_id = $custom_fields_config->ivao;
        $vatsim_field_id = $custom_fields_config->vatsim;
            
        $data = DB::table('fieldvalues')
        ->whereIn('fieldid', [$ivao_field_id, $vatsim_field_id])
        ->where('pilotid', $pilotid)
        ->pluck('value', 'fieldid')
        ->toArray();
    
        $output = [
            'ivao' => $this->convert_to_integer($data[$ivao_field_id] ?? null),
            'vatsim' => $this->convert_to_integer($data[$vatsim_field_id] ?? null),            
        ];
        
        return $output;
    }

    /**
     * get_all_pilots
     *
     * @return void
     */
    public function get_all_pilots() {
        $pilots = Pilots::select($this->fetchable_from_model)->get();        
        return $this->json([
            'total' => $pilots->count(),
            'data' => $pilots->map(function($pilot) {                
                // $pilot->pilot_va_id = $pilot->code.$pilot->pilotid;      
                // $pilot->ivao_vid = null;
                // $pilot->vatsim_cid = null;  
                return $pilot;
            }),
        ]);
    }
    
    /**
     * find_pilot
     *
     * @return void
     */
    public function find_pilot() {
        $pilot_id = $this->get('id');
        if(!is_null($pilot_id)) {
            $pilot = Pilots::select($this->fetchable_from_model)->where('pilotid', $pilot_id)->get();            
            if($pilot == '[]') {

                return $this->json([
                    'message' => "No pilot found with ID {$pilot_id}",
                    'data' => false,
                ]);

                // throw new Exception("No pilot found with ID {$pilot_id}");
            } else {

                
                return $this->json(
                    [
                        'message' => 'Pilot found',
                        'data' => $pilot->map(function($pilot) {    
                            
                            $custom_fields = $this->get_custom_fields($pilot->pilotid);

                            $pilot->pilot_va_id = $pilot->code.$pilot->pilotid;      
                            $pilot->ivao_vid = $custom_fields['ivao'];
                            $pilot->vatsim_cid = $custom_fields['vatsim'];
                            return $pilot;
                        }),
                    ]
                );    
            }
            
        } else {
            throw new Exception("Looks like pilot ID was not passed in the URI");
        }    
    }
    
    /**
     * _get_pilot_by_vid
     *
     * @param  mixed $network_id
     * @return void
     */
    public function _get_pilot_id_using_network_id(?int $network_id, string $network = 'IVAO') {

        $response = [];

        if(!is_null($network_id)) {
            
            $check_custom_field = DB::table('fieldvalues')->select('*')->where('value', $network_id)->first();                    
                
            if(!is_null($check_custom_field) && $check_custom_field != '[]') {
                $pilot = Pilots::select($this->fetchable_from_model)
                // ->where('confirmed', 1)
                ->where('pilotid', $check_custom_field->pilotid)
                ->first();            

                if($pilot == '[]') {
                    // No pilots found. 
                    $response = [
                        'message' => "3rd Level: No pilot found with Network ID {$network_id}",
                        'data' => null,
                    ];                    
                } else {                

                    // Pilot found. 
                    $response = [
                        'message' => "3rd Level: Pilot found with VID {$network_id}",                        
                        'data' => $pilot,
                    
                        // 'data' => $pilot->map(function($pilot) use ($network) {                                
                        //     // $custom_fields = $this->get_custom_fields($pilot->pilotid);
                        //     $pilot->pilot_va_id = $pilot->code.$pilot->pilotid;      
                        //     // $pilot->ivao_vid = $custom_fields['ivao'];
                        //     // $pilot->vatsim_cid = $custom_fields['vatsim'];
                        //     return $pilot;
                        // }),
                    ];
                }
            } else {
                $response = [
                    'message' => "2nd Level: No pilots found with {$network} network ID: {$network_id}",
                    'data' => null,
                ]; 
            }               
        } else {
            $response = [
                'message' => "1st Level: Invalid network ID {$network_id}",
                'data' => null,
            ];  
        }  
        
        return $response;
    }
    
    /**
     * find_pilot_by_vid
     *
     * @return void
     */
    public function find_pilot_by_vid() {
        $network_id = $this->get('id');
        if(!is_null($network_id)) {
            $check_custom_field = DB::table('fieldvalues')->select('*')->where('value', $network_id)->first();                    
            if(!is_null($check_custom_field) && $check_custom_field != '[]') {
                $pilot = Pilots::select($this->fetchable_from_model)->where('pilotid', $check_custom_field->pilotid)->get();            
                if($pilot == '[]') {
                    return $this->json([
                        'message' => "No pilot found with VID {$network_id}",
                        'data' => false,
                    ]);                    
                } else {

                    
                    return $this->json(
                        [
                            'message' => "Pilot found with VID {$network_id}",
                            'data' => $pilot->map(function($pilot) {                                
                                $custom_fields = $this->get_custom_fields($pilot->pilotid);

                                $pilot->pilot_va_id = $pilot->code.$pilot->pilotid;      
                                $pilot->ivao_vid = $custom_fields['ivao'];
                                $pilot->vatsim_cid = $custom_fields['vatsim'];
                                return $pilot;
                            }),
                        ]
                    );    
                }
            } else {
                return $this->json([
                    'message' => "No pilot found with VID {$network_id}",
                    'data' => false,
                ]);     
            }                   
        } else {
            throw new Exception("Looks like pilot ID was not passed in the URI");
        }  
    }
}

?>