<?php
/**
iCrew Admin Class
Author: Leonard Selvaraja 
2017.

INSERT INTO `iflyvaco_phpvms`.`phpvms_settings` (`id`, `friendlyname`, `name`, `value`, `descrip`, `core`) VALUES ('9', 'iCrew Version', 'ICS_VERSION', '', 'The version of iCrew Package which you are using', '1'), ('10', 'iCrew License Key', 'KEY', '', 'Your key for using iCrew Skin and addons. If you face any issues, contact iCrewSystems and get a new key', '1');
**/
class ICSAdmin extends CodonData
{
  public static function success(){
    echo '<span style="color:green"><Strong>ACTIVE</strong></span>';
    
  }
  
  public static function error(){
    echo '<span style="color:red"><Strong>ERROR</strong></span>';
  }
  
  public static function loading(){
    echo '<script type="text/javascript">
$(function() {
setTimeout(function() { $("#fadeout").fadeOut(150); }, 4000);
})
</script>
<span id="fadeout"> <img src="http://icrew.piavirtual.org/lib/images/loading.gif" /></span>
';

    
  }
	public static function phonetic($char)
    {
        $nato = array(
            "a" => "alfa", 
            "b" => "bravo", 
            "c" => "charlie", 
            "d" => "delta", 
            "e" => "echo", 
            "f" => "foxtrot", 
            "g" => "golf", 
            "h" => "hotel", 
            "i" => "india", 
            "j" => "juliett", 
            "k" => "kilo", 
            "l" => "lima", 
            "m" => "mike", 
            "n" => "november", 
            "o" => "oscar", 
            "p" => "papa", 
            "q" => "quebec", 
            "r" => "romeo", 
            "s" => "sierra", 
            "t" => "tango", 
            "u" => "uniform", 
            "v" => "victor", 
            "w" => "whisky", 
            "x" => "x-ray", 
            "y" => "yankee", 
            "z" => "zulu", 
            "0" => "zero", 
            "1" => "one", 
            "2" => "two", 
            "3" => "three", 
            "4" => "four", 
            "5" => "five", 
            "6" => "six", 
            "7" => "seven", 
            "8" => "eight", 
            "9" => "niner"
            );
 
        return $nato[strtolower($char)];
    }
    
    function findreg(){
        	$l = $registration;
        	$regi = (string)$l;
        	$stringlength = count($regi);
        	for($x = 0; $x <= 5; $x++)
        	{
        		echo ICSAdmin::phonetic($regi[$x]).' ';
        	}	
        	}
  
  public static function findLogs($params, $count = '', $start = '') {
        $sql = 'SELECT l.*, p.* 
				FROM realops_logbook l
				INNER JOIN ' . TABLE_PREFIX . 'pilots p ON l.pilotid = p.pilotid ';

        /* Build the select "WHERE" based on the columns passed */
        $sql .= DB::build_where($params);

        $sql .= ' ORDER BY l.datestamp DESC';

        if (strlen($count) != 0) {
            $sql .= ' LIMIT ' . $count;
        }

        if (strlen($start) != 0) {
            $sql .= ' OFFSET ' . $start;
        }

        $ret = DB::get_results($sql);
        return $ret;
    }

    public static function addLog($pilotid, $message) {
        $message = DB::escape($message);

        $sql = "INSERT INTO realops_logbook (`pilotid`, `datestamp`, `message`)
				VALUES ('{$pilotid}', NOW(), '{$message}')";

        DB::query($sql);
    }
  
  public static function getSetting($name) {
        return DB::get_row('SELECT * FROM ' . TABLE_PREFIX . 'settings 
					WHERE name=\'' . $name . '\'');
    }
  
  public static function sec1(){
    $sec1 = '<div class="ui-widget" style="margin: 4px 0 4px 0">
	            <div style="padding: 0pt 0.7em;" class="ui-state-error  ui-corner-all"> 
		          <p><span style="float: left; margin-right: 0.3em;" class="ui-icon ui-icon-alert"></span> 
		          iCrew Notification <br> <em>
		          ';
            
    echo $sec1;
  }
  public static function sec2(){
   
	  $sec2 = '</em></p>
        	  </div>
            </div>';
            
    echo $sec2;
  }
  
	
	public static function checkupdate()
	{
	  $ics_current_ver = ICSAdmin::GetSetting('ICS_VERSION');
		$current_version = $ics_current_ver->value;
		$updated_version = trim(file_get_contents(CHK_URL.'/license/Version/'.LIC.''));;
		$a = $current_version ;
		$b = $updated_version;
		if($current_version == $updated_version)
		{
		  $update_ver = 'Running on latest version';
		}
		else
		{
		  $update_ver = 'There is a new Update for your iCrew. Get in touch with Leonard';
		  ICSAdmin::sec1(); echo $update_ver; ICSAdmin::sec2();  
		}
		 
	}
	
	public static function sendmail() {
		$fromname = 'Auto mail';
		$fromemail = 'info@icrewsystems.com';
		$message = Auth::$pilot->code.' '.Auth::$pilot->pilotcode; 
		$subject = 'TEST';
		Util::SendEmail($email, $subject, $message, $fromname='', $fromemail='');
	}
	
	public static function expiry(){
    $completion_date = strtotime(file_get_contents(CHK_URL.'/license/finishdates/'.LIC.''));
    if(!$completion_date) {
    	ICSAdmin::error(); echo ' TEMPORARY LICENSE MODE';
    	return;
    }
    $d = date(strtotime("+6 months", $completion_date));
    $date=$d;
    $diff=$date-time();
    $days=floor($diff/(60*60*24));
    $hours=round(($diff-$days*60*60*24)/(60*60));
    $date1 = date('d F Y',$d); 
    if($days < 15 && $days > 0) {
        ICSAdmin::sec1(); echo 'Your service ends in '.$days.' days and '.$hours.' hours'; ICSAdmin::sec2(); 
      }
    elseif($days > 0)
    {
      echo "$date1 ($days days $hours hours remaing)";
    }
    else
    {
      echo 'Service EXPIRED, Contact iCrew to Renew';
    }
    
    
	}
	
	public static function graphicssupport() {
	  $getstatus = file_get_contents(CHK_URL.'/license/support/graphics/'.LIC.'');
	  if($getstatus == 1){
	    echo '<span style="color:green"><Strong>ACTIVE</strong></span>';
	  }
	  else
	  {
	    echo '<span style="color:red"><Strong>NOT PURCHASED</strong></span>';
	  }
	}
	
	public static function techsupport() {
	  $getstatus = file_get_contents(CHK_URL.'/license/support/tech/'.LIC.'');
	  if($getstatus == 1){
	    echo '<span style="color:green"><Strong>ACTIVE</strong></span>';
	  }
	  else
	  {
	    echo '<span style="color:red"><Strong>NOT PURCHASED</strong></span>';
	  }
	}
	
	
    
  public static function skincheck() {
				$skin = ICSAdmin::GetSetting('CURRENT_SKIN');
				$currentskin = $skin->value;
				if($currentskin != 'iCrew')
				{
				  ICSAdmin::sec1(); echo SITE_NAME.' is not running on iCrew v4, if you donot use iCrew skin, phpVMS may not function properly. Click <a href="'.adminurl('/settings').'">here</a>'; ICSAdmin::sec2();
				}
  }
  
   public static function cabin_crew($crew_limit) {
   	
				if($crew_limit == '') {
					$crew_limit = 5;
				}			
				$sql = "SELECT * FROM `cabin_crew_names` ORDER BY RAND() LIMIT $crew_limit; ";
				return DB::get_results($sql);
  }
  
  public static function get_pilot($pilot_limit) {
   	
				/*$sql = "SELECT * FROM " . TABLE_PREFIX . "pilots  WHERE `retired` = 0 ORDER BY RAND() LIMIT 2; ";*/
				$sql = "SELECT * FROM `cabin_crew_names` ORDER BY RAND() LIMIT $pilot_limit; ";
				return DB::get_results($sql);
  }
  
  public static function countcrew()
	{
		$query = "SELECT * FROM `cabin_crew_names` WHERE crew_base = 0";
		$results = DB::get_results($query);
		return DB::num_rows($results);
	}
  
  public static function currentskin() {
        
		    $skin = ICSAdmin::GetSetting('CURRENT_SKIN');
				$currentskin = $skin->value;
			if($currentskin != 'iCrew')
			{
			  ICSAdmin::error(); echo ' '.$currentskin;
			}
			else 
			{
			  ICSAdmin::success(); echo ' '.$currentskin;
			}
  }
  
  public static function send_new_mail($who_to, $who_from, $subject, $newmessage, $notam, $thread_id) {
  	
        $sql="INSERT INTO ".TABLE_PREFIX."airmail (`who_to`, `who_from`, `date`, `subject`, `message`, `notam`, `thread_id`)
			VALUES ('$who_to', '$who_from', NOW(), '$subject', '$newmessage', '$notam', '$thread_id')";

        DB::query($sql);

        $code = DB::errno();
        if ($code != 0){
            $message = DB::error();
            throw new Exception($message, $code);
        }

        return;
    }
    
    /*Real Ops Stuff*/
    public static function realops_request($pilotid, $datestamp, $duty_date, $start_time, $end_time, $legs, $type_of_flights, $message) {
		
		$sql = "INSERT INTO `realops_request` (`pilotid`, `datestamp`, `duty_date`, `start_time`, `end_time`, `legs`,
			`type_of_flights`, `message`) 
			VALUES ('$pilotid', '$datestamp', '$duty_date', '$start_time', '$end_time', '$legs', '$type_of_flights', '$message')";
        DB::query($sql);
        return;
    }
    
    public static function mark_as_banned($pilotid) {
    	$sql = "UPDATE `phpvms_pilots` SET `realops_status` = '2' WHERE `pilotid` = $pilotid";
    	DB::query($sql);
    }
    
     public static function realops_settings_save($module_status, $default_vmoney) {
		
		$sql = "UPDATE `realops_settings` SET (`module_status`, `default_vmoney`)
				VALUES ('$module_status', '$default_vmoney') WHERE `setting_id` = 1";
				
	/*	$sql = "UPDATE `realops_settings` SET `module_status` = '$module_status', `default_vmoney` = '$default_vmoney' WHERE `setting_id` = 1"; */
		DB::query($sql);
        return;
    }
    
    public static function get_all_realops_settings() {
    	$sql = "SELECT * FROM `realops_settings` WHERE `setting_id` = 1";
    	return DB::get_results($sql);
    }
    
    public static function reduce_money($pilotid, $money) {
    	$pilotdata = PilotData::getPilotData($pilotid);
    	$account_balance = $pilotdata->totalpay;
		$charges = $account_balance - $money ;
		$sql = "UPDATE `".TABLE_PREFIX."pilots` SET `totalpay` = '$charges' WHERE `phpvms_pilots`.`pilotid` = $pilotid";
		DB::query($sql);
		$type = 'Debit';
		self::passbook_entry($pilotid, $transaction_id, $type, $money, $charges);
		
    }
    
    public static function passbook_entry($pilotid, $transaction_id, $type, $money, $charges) {
    	$type = 'deduct';
    	$date = date('d-m-Y', time());
    	switch ($type) {
    		case 'add':
    			$transaction_type = 'Credit';
    		break;
    		case 'sub':
    			$transaction_type = 'Debit';
    		break;
    		default:
    			$transaction_type = 'Debit';
    		break;
    	}
    	if($transaction_id == 0) {
    		$transaction_id = time();
    	}
    	
		$sql = "INSERT INTO `realops_bank` (`transaction_id`, `transaction_type`, `pilotid`, `amount`, `balance`, `date`)
				VALUES ('$transaction_id', '$transaction_type', '$pilotid', '$money', '$charges', '$date')";
        DB::query($sql);
        return;
    }
   
	public static function get_all_passbook_entries() {
    	$sql = "SELECT * FROM `realops_bank` ORDER BY id DESC";
    	return DB::get_results($sql);
    }
    
    public static function passboook_entry_pilot($pilotid) {
    	$sql = "SELECT * FROM `realops_bank` WHERE `pilotid` = $pilotid ORDER BY id DESC";
    	return DB::get_results($sql);
    }
    
    public static function passboook_entry_id($id) {
    	$sql = "SELECT * FROM `realops_bank` WHERE `id` = $id";
    	return DB::get_results($sql);
    }
    
    public static function passbook_entry_del($req_id)
		{
			$sql="DELETE FROM realops_bank WHERE id = '$req_id'";
			DB::query($sql);
		}
    
    public static function mark_as_processed($id) {
    	$sql = "UPDATE `realops_request` SET `processed` = 1 WHERE `id` = $id";
    	DB::query($sql);
    }
    
    public static function get_all_processed() {
    	$sql = "SELECT * FROM `realops_request` WHERE `processed` = 1 ";
    	return DB::get_results($sql);
    }
    
    
    public static function get_all_rops() {
    	$sql = "SELECT * FROM `realops_request` ";
    	return DB::get_results($sql);
    }
    
    public static function get_all_archived() {
    	$sql = "SELECT * FROM `realops_history` ";
    	return DB::get_results($sql);
    }
    
    public static function get_pilot_last_archived_id($pilotid) {
    	$sql = "SELECT * FROM `realops_history` WHERE pilotid = '$pilotid' ORDER by datestamp LIMIT 1";
    	return DB::get_results($sql);
    }
	
	public static function get_all_pilot($pilotid) {
    	$sql = "SELECT * FROM `realops_request` WHERE pilotid = '$pilotid'";
    	return DB::get_results($sql);
    }
		public static function delete_all_requests()
		{
			$sql="TRUNCATE TABLE realops_request";
			DB::query($sql);
		}
		
		public static function delete_rop_request($aid)
		{
			$sql="DELETE FROM realops_request WHERE id = '$aid'";
			DB::query($sql);
		}
		
		public static function delete_rop_pilot($pilotid)
		{
			$sql="DELETE FROM realops_request WHERE pilotid = '$pilotid'";
			DB::query($sql);
		}
		
		public static function delete_rop_id($req_id)
		{
			$sql="DELETE FROM realops_request WHERE id = '$req_id'";
			DB::query($sql);
		}
		
		public static function archive($id)
		{
			$sql = "INSERT INTO `realops_history` (`id`, `pilotid`, `datestamp`, `duty_date`, `start_time`, `end_time`, `legs`,
			`type_of_flights`, `message`, `processed`) SELECT id, pilotid, datestamp, duty_date, start_time, end_time, legs, type_of_flights, message, processed FROM `realops_request` WHERE id = '$id'";
        	DB::query($sql);
        	
        return;
		}
		
		public static function Rop_Notify($notify_clr, $notify_msg, $delay, $commence) {
			
			if(!$delay) {
				$delay = 5000;
			}
			if(!$commence) {
				$commence = 2000;
			}
			?>
			<script>
    			$(function() {
    			setTimeout(function() {
    			$.bootstrapGrowl("<h4>RealOps <strong>Notification </strong> </h4><?php echo $notify_msg ?> ", {
    			ele: 'body', // which element to append to
    			type: '<?php echo $notify_clr; ?>', // (null, 'info', 'danger', 'success')
    			offset: {from: 'top', amount: 20}, // 'top', or 'bottom'
    			align: 'right', // ('left', 'right', or 'center')
    			width: 250, // (integer, or 'auto')
    			delay: <?php echo $delay; ?>, // Time while the message will be displayed. It's not equivalent to the *demo* timeOut!
			    allow_dismiss: true, // If true then will display a cross to close the popup.
    			stackup_spacing: 10 // spacing between consecutively stacked growls.
    			});
    			}, <?php echo $commence; ?>);
    			});      
			</script>
			<?php
		}
	
}
	?>