<?php session_start(); ?>
<?php require_once '../../connections/meekro/db.class.php'; ?>
<?php require_once 'functions.php';?>
<?php
   
if(isset($_POST['declarant-tin'])){
    $tin = $_POST['declarantTIN'];
    $licence = $_POST['declarantLicence'];
    $query = DB::queryFirstRow("SELECT * FROM singlePage_applicants WHERE tin=%s", $_POST['declarantTIN']);
        if($query){
          $_SESSION['success'] = " Records Found";
          echo '<script>location.href="declarants.php?tin='.$tin.'"</script>';
	     // header('location: declaranfffts.php?tin=' . $_POST['declarantTIN']);
    }else{
       $api_url = "https://apps.firs.gov.ng/apis/tinvalidation/".$_POST['declarantTIN'];
   try {
          $response = file_get_contents($api_url);
          if ($response !== false) {
               $data = json_decode($response, true);
               // Check if JSON decoding was successful
                if (json_last_error() === JSON_ERROR_NONE) {
                     $tin = $data['TIN']; 
                    $name = $data['TaxPayerName']; 
                    $email = strtolower($data['Email']);  
                    $phone = $data['Phone']; 
                    $address = $data['Address']; 
                    $rcNumber = $data['RCNumber'];
                    
                            DB::insertIgnore('singlePage_applicants', [
                			  'tin' => $tin,
                			  'licence' => $licence,
                			  'email' => $email,
                			  'phone' => $phone,
                			  'order_id' => '12345',
                			  'paid_amount' => '5000',
                			  'payment_status' => 'PAID',
                			  'payment_message' => 'Successful', 
                			  'remitta_reference' => '12345',
                			  'address' => $address,
                			  'access_level'=>'3',
                			  'rc_number' => $rcNumber,
                			  'fullname' => $name,
                			  'company_name' => $name,
                			  'date_created' => time()
                			]);
                			
                		        $_SESSION['success'] = " Added Succesful";
                		       // header('Location: declarants.php?tin=' . urlencode($tin));
                		         echo '<script>location.href="declarants.php?tin='.$tin.'"</script>';
                         
                             
                                                    		
                } else {
                    $_SESSION['fail'] = ' Error. Failed to decode JSON ' . json_last_error_msg();
                    header('Location: index.php');
                }
          } else {
               $_SESSION['fail'] = ' Error. Failed to fetech TIN records ';
               header('Location: index.php');
                                                       
            }
   } catch (Exception $e) {
            $_SESSION['fail'] = ' Error. An error occurred ' . $e->getMessage();
            header('Location: index.php');
        }  
    }
                                             
}
    
//ADD FIELD AGENT
if(isset($_POST['add-field-agent'])){
    $rcNumber = $_POST['companyRc'];
    $companyTIN = $_POST['companyTin'];
    $phone = $_POST['phone'];
    $email = strtolower($_POST['email']);
    $tin = $_POST['tin'];
    $nin = $_POST['nin'];
    $query = DB::queryFirstRow("SELECT COUNT(company_rc_no) AS totalDirector FROM singlePage_authorized_users WHERE company_rc_no = '$rcNumber' AND company_tin='$companyTIN' AND status!='Active'");
    if($query['totalDirector'] < 1000){
              $query2 = DB::queryFirstRow("SELECT email FROM singlePage_applicants WHERE email='$email'");
              if($query2){
                  $_SESSION['fail'] = ' Error. You are not allowed to use the Company Email for an Employee. Please provide a different email ';
                  header('Location: ' . $_SERVER['HTTP_REFERER']);
              }else{
                $check = DB::queryFirstRow("SELECT * FROM singlePage_authorized_users WHERE  email = %s ", $email);
                    if ($check) {
                        if ($check['phone'] == $phone) {
                            $_SESSION['fail'] = 'Error: This phone number is already in use.';
                        } elseif ($check['email'] == $email) {
                            $_SESSION['fail'] = 'Error: This email is already in use.';
                        } elseif ($check['nin'] == $nin) {
                            $_SESSION['fail'] = 'Error: This NIN is already in use.';
                        }
                        header('Location: ' . $_SERVER['HTTP_REFERER']);
                        exit; // Ensure the script stops execution after the redirect.
                    }else{
                          
                                  
                                     $res = DB::insert('singlePage_authorized_users', array(
                                    'title' => $_POST['title'],
                                    'surname' => $_POST['surname'],
                                    'firstname' => $_POST['firstname'],
                                    'othername' => $_POST['othername'],
                                    'applicant_id' => $rcNumber,
                                    'phone' => $_POST['phone'],
                                    'email' => $_POST['email'],
                                    'gender' => $_POST['gender'],
                                    'tin' => $_POST['tin'],
                                    'nin' => $_POST['nin'],
                                    'passport' => 'NA',
                                    'company_rc_no' => $rcNumber,
                                    'company_tin' => $companyTIN,
                                    
                                   
                                    'home_address' => $_POST['address'],
                                    'status' => 'Active',
                                    'date_created' => time()
                                        )
                                            
                                    );
                                        if($res){
                                             $_SESSION['success'] = " Uploaded Successfully";
                                            header('Location: ' . $_SERVER['HTTP_REFERER']);
                                            
                                        }else{
                                             $_SESSION['fail'] = ' Error. This Email is in used already ';
                                             header('Location: ' . $_SERVER['HTTP_REFERER']);
                                        }
                                
                          }  
              }
         
        }else{
        	$_SESSION['fail'] = ' Error. You have reached the maximum number (1000) of Employee for this Licence ';
            header('Location: ' . $_SERVER['HTTP_REFERER']);
        }
}


// UPDATE EMPLOYEE

if(isset($_POST['update-employee'])){
    // echo "dlkjd";
    $companyTin = $_POST['companyTin'];
    $companyLicence = $_POST['companyLicence'];
    $employeeId = $_POST['userId'];
    $phone = $_POST['phone'];
    $email = strtolower($_POST['email']);
    $tin = $_POST['tin'];
    $nin = $_POST['nin'];
    $surname = $_POST['surname'];
    $firstname = $_POST['firstname'];
    $othername = $_POST['othername'];
    $gender = $_POST['gender'];
    $address = $_POST['address'];
    $returnLink = 'index.php?tin='.$companyTin.'&licence='.$companyLicence;
    $res = DB::query("UPDATE singlePage_authorized_users SET firstname='$firstname', surname='$surname', othername='$othername', phone='$phone', email='$email', gender='$gender', home_address='$address', tin='$tin', edit_status='Edited' 
                        WHERE auth_user_id='$employeeId' ");
                        
    if(DB::affectedRows() == 1){
                 $_SESSION['success'] = " Updated ";
                 header('Location: ' . $returnLink); 
           }else{
                $_SESSION['fail'] = " Fetal Error: An error occured, please try again or contact the system Administrator";
                header('Location: ' . $_SERVER['HTTP_REFERER']);
           }                    
}


//BLOCK EMPLOYEE
  if (isset($_POST['block'])) {
     $blockId = $_POST['block'];
     $reason = $_POST['blockReason'];
    
           $res = DB::query("UPDATE singlePage_authorized_users SET status='Inactive', reason='$reason' WHERE auth_user_id='$blockId' ");
           if(DB::affectedRows() == 1){
                 $_SESSION['success'] = " Account Blocked";
                 header('Location: ' . $_SERVER['HTTP_REFERER']); 
           }else{
                $_SESSION['fail'] = "  An error occured, Please Try again";
                header('Location: ' . $_SERVER['HTTP_REFERER']);
           }
        
    }
    
//UNBLOCK EMPLOYEE
  if (isset($_POST['unblock'])) {
     $unBlockId = $_POST['unblock'];
     $reason = $_POST['unblockReason'];
           $res2 = DB::query("UPDATE singlePage_authorized_users SET status=%s, reason=%s WHERE auth_user_id=%i", 'Active', $reason, $unBlockId);
          // echo $unBlockId;
           if(DB::affectedRows() == 1){
                 $_SESSION['success'] = " Account Activated";
                //  echo "true";
                 header('Location: ' . $_SERVER['HTTP_REFERER']); 
           }else{
                $_SESSION['fail'] = " An error occured, Please Try again";
                //  echo "false";
                header('Location: ' . $_SERVER['HTTP_REFERER']);
           }
        
    }




   
 
?>

