<?php

namespace App\Controllers;

use App\Models\Firc\Md_login;
$session = \Config\Services::session();

use PhpOffice\PhpSpreadsheet\Helper\Sample;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Firc extends BaseController
{
    
    
    public function __construct() {
         $this->Md_login = new Md_login();
    }
    
    public function index(): string
    {
        return view('index');
    }
    
    
    
    public function ReactLoginAction() 
    {   
   
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
        
        $datas = json_decode(file_get_contents("php://input"), true);
        $Mobile=$datas['Username'];
        $Password=$datas['Password'];

        if (!empty($Mobile) && !empty($Password)) 
        {
            $EncryPassword = md5($Password);

            // $year = date('Y');
            // $table = "login";
            // $fields = array('*');
            // $condition = array('mobile' => $Mobile, 'password' => $EncryPassword, 'status' => '1');
            // $arrayUser = $this->Md_database->getData($table, $fields, $condition, 'id DESC', '1');

           
            $arrayUser=$this->Md_login->loginCheck($Mobile, $EncryPassword);
            
         
            if (empty($arrayUser)) {
                
                $final = array('status' => 2, 'sms' =>'Sorry! mobile or password is wrong.','url'=>'login','logintype'=>'user');
                echo json_encode($final);
                exit();   

            } else if (!empty($arrayUser) && $arrayUser->usr_status == "2") 
            {
                
                $final = array('status' => 2, 'sms' =>'Sorry! student not active..','url'=>'login','logintype'=>'user');
                echo json_encode($final);
                exit();            

            } else if (!empty($arrayUser) && $arrayUser->usr_status ==1) {


            $final = array('status' => 1, 'sms' =>'Thanks! you are login successfully.','url'=>'dashboard','logintype'=>'user','loginid'=> $arrayUser->pk_user_id );
            echo json_encode($final);
            exit();
            }

        } else {

            $final = array('status' => 2, 'sms' =>'Sorry...something went wrong.');
            echo json_encode($final);
            exit();

        }
    }
    
  
    public function billingList() 
    {
   
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
     
 
        $datas = json_decode(file_get_contents("php://input"), true);
        
        
         $res_result=$this->Md_login->getBillingData();
         
        if(!empty($res_result)){
        $final = array('status' => 1,'res_result'=>$res_result, 'sms' =>'Thanks! billing data fetch.');
        echo json_encode($final);
        exit();
        }else {
               $final = array('status' => 2, 'msg' =>'Sorry! no more record found');
            echo json_encode($final);
            exit();  
        }
    }
    
    
    public function billingFileUpload() 
    {
        try {
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
     
 
        $datas = json_decode(file_get_contents("php://input"), true);
        $file = $this->request->getFile('file');

        if (!empty($file)) 
        {

        if ($file->isValid() && !$file->hasMoved()) {

            // Generate new random name
            $newName = $file->getRandomName();
            // Move file to writable/uploads
            $upload_dir='upload/firc/billing/';
            $file->move($upload_dir, $newName);
            
            
            $table = "billing_file_upload";
            $insertData = array(
                'file_name' => $newName,
                'upload_dir' => $upload_dir,
                'status' => '1',
                'created_by'=>1,
                'created_date' => date('Y-m-d H:i:s'),
                'created_ip_address' => $_SERVER['REMOTE_ADDR']
            );

            $this->Md_login->insertData($table, $insertData);
            
            
            $filePath="upload/firc/billing/Book1.xlsx";
            
             $this->excelRead($upload_dir.$newName);

            $final = array('status' => 1, 'msg' =>'Thanks! File Uploaded Successfully.','url'=>'dashboard','logintype'=>'user','loginid'=> $newName);
            echo json_encode($final);
            exit();

        } else {

            $final = array('status' => 2, 'msg' =>'Sorry! File Upload Failed','url'=>'login','logintype'=>'user');
            echo json_encode($final);
            exit();  

        }
        

        } else {

            $final = array('status' => 2, 'msg' =>'Sorry! File Upload Failed','url'=>'login','logintype'=>'user');
            echo json_encode($final);
            exit();  

        }
    } catch (Exception $e) 
        {
            
            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit(); 
        }
    }
    public function getCompany() 
    {
        try {
        
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
     
 
        $datas = json_decode(file_get_contents("php://input"), true);
        
        
         $res_result=$this->Md_login->getCompany();
         
        if(!empty($res_result)){
        $final = array('status' => 1,'res_result'=>$res_result, 'sms' =>'Thanks! get company data fetch.');
        echo json_encode($final);
        exit();
        }else {
               $final = array('status' => 2, 'msg' =>'Sorry! no more record found');
            echo json_encode($final);
            exit();  
        }
        
    } catch (Exception $e) 
        {
            
            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit(); 
        }
    }
    
    
     public function getCustomerCompanyWise() 
    {
        try {
        
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
     
 
        $datas = json_decode(file_get_contents("php://input"), true);
        
        $file = $datas['company'];
        
        if(!empty($file))
        {
         $res_result=$this->Md_login->getCustomerCompanyWise($file);
         
        if(!empty($res_result)){
            $final = array('status' => 1,'res_result'=>$res_result, 'sms' =>'Thanks! get company data fetch.');
            echo json_encode($final);
            exit();
        }else {
            $final = array('status' => 2, 'msg' =>'Sorry! no more record found');
            echo json_encode($final);
            exit();  
        }
        
        }else {
               $final = array('status' => 2, 'msg' =>'Sorry! no more record found');
            echo json_encode($final);
            exit();  
        }
        
    } catch (Exception $e) 
        {
            
            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit(); 
        }
    }
     public function getBillingResult() 
    {
        try {
        
        header("Access-Control-Allow-Origin: *");
        // If you need to allow specific methods
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
        // If you need to allow specific headers
        header("Access-Control-Allow-Headers: Content-Type, Authorization");
     
 
        $datas = json_decode(file_get_contents("php://input"), true);
        
        $company= $datas['company'];
        $customer = $datas['customer'];
        $firc_amount = $datas['firc_amount'];
        
        if(!empty($company) && !empty($customer) && !empty($firc_amount))
        {
            
         $res_result=$this->Md_login->getBillingResult($company,$customer);
         
        if(!empty($res_result)){
            
            $tempResult = [];
            $received_foreign_currency=0;
         
                        
            foreach ($res_result as $rows)
            {
                   
            
                $received_foreign_currency= (float) $rows['received_foreign_currency'];
                   
                if($received_foreign_currency==0)
                {
                  
                   $foreign_currency= (float) $rows['foreign_currency'];
                   $remaning_foreign_currency= (float) $rows['remaning_foreign_currency'];
                    if($firc_amount>0 && $firc_amount>=$foreign_currency)
                    {
                        $received_foreign_currency=$foreign_currency;
                        $firc_amount=$firc_amount-$foreign_currency;
                        $remaning_foreign_currency=(float) $foreign_currency-$firc_amount;
                    }else {
                        $received_foreign_currency=$firc_amount;
                        $firc_amount=0;
                        $remaning_foreign_currency=(float) $foreign_currency-$received_foreign_currency;
                        
                        
                        
                    }
                    
                    if($foreign_currency==$remaning_foreign_currency)
                    {
                        $remaning_foreign_currency=0;
                    }
                }
                
                $tempRow = [];
            
                $tempRow['invoice_date'] = date('d-M-Y', strtotime($rows['invoice_date']));
                $tempRow['invoice_no'] = $rows['invoice_no'];
                $tempRow['currency'] = $rows['currency'];
                $tempRow['foreign_currency'] =number_format($foreign_currency, 2, '.', '');
                $tempRow['exch_rate'] =number_format($rows['exch_rate'], 2, '.', '');
                $tempRow['amount_in_inr'] =number_format($rows['amount_in_inr'], 2, '.', '');
                $tempRow['received_foreign_currency'] =number_format($received_foreign_currency, 2, '.', '');
                $tempRow['remaning_foreign_currency'] =number_format($remaning_foreign_currency, 2, '.', '');
                $tempRow['pk_id'] = $rows['pk_id'];
            
                $tempResult[] = $tempRow;
            }
            
            
            $final = array('status' => 1,'res_result'=>$tempResult, 'sms' =>'Thanks! get the data.');
            echo json_encode($final);
            exit();
        }else {
            $final = array('status' => 2, 'msg' =>'Sorry! no more record found');
            echo json_encode($final);
            exit();  
        }
        
        }else {
               $final = array('status' => 2, 'msg' =>'Sorry! company or customer or firc amount is not selected');
            echo json_encode($final);
            exit();  
        }
        
    } catch (Exception $e) 
        {
            
            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit(); 
        }
    }
    
    
   public function excelRead($filename=null)
    {
         try {
        // error_reporting(1);
        require_once __DIR__ . '/../../../services.mvpm.org/excel/Bootstrap.php';

         // Load Excel File
            $spreadsheet = IOFactory::load($filename);

            // Get Active Sheet
            $sheet = $spreadsheet->getActiveSheet();

            // Convert to Array
            $data = $sheet->toArray();
  

        $i=0;
        if(!empty($data))
        {
            foreach($data as $rows){
                if($i>1){
                    
                    $company_divison=$rows[0];
                    $financial_year=$rows[1];
                    $months=$rows[2];
                    $invoice_dateTemp=$rows[3];
                    $invoice_no=$rows[4];
                    $customer_name=$rows[5];
                    $address=$rows[6];
                    $country=$rows[7];
                    $verticle=$rows[8];
                    $bu_l1=$rows[9];
                    $bu_l2=$rows[10];
                    $type=$rows[11];
                    $currency=$rows[12];
                    $total_billed_hrs=$rows[13];
                    $rate_hr=$rows[14];
                    $foreign_currency=number_format((float)str_replace(',', '', $rows[15]), 2, '.', '');
                    $exch_rate=$rows[16];
                    $amount_in_inr=number_format((float)str_replace(',', '', $rows[17]), 2, '.', '');
                    $geography=$rows[18];
                    $sales_person=$rows[19];
                    $project_name=$rows[20];
                    $project_id=$rows[21];
                    $inv_to_place=$rows[22];
                    $po=$rows[23];
                    $offshore_onsite=$rows[24];
                    $softex=$rows[25];
                    // $country=$rows[22];


                    if(!empty($invoice_dateTemp) && $invoice_dateTemp!="#N/A"){
                        if (strpos($invoice_dateTemp, '-') !== false) {
                        $parts = explode('-', trim($invoice_dateTemp));
                        } elseif (strpos($invoice_dateTemp, '/') !== false) {
                             $parts = explode('/', trim($invoice_dateTemp));
                        }
                        $day = $parts[0];
                        $month = date('m', strtotime($parts[1]));
                        $year = (strlen($parts[2]) == 2) ? '20' . $parts[2] : $parts[2];
                        $invoice_date = $year . '-' . $month . '-' . $day;
                    }else {
                        $invoice_date=null;
                    }
                    
                    if("0000-00-00"==$invoice_date)
                    {
                        $invoice_date=null;
                    }

           
                    $table = "billing";
                    $insertData = array(
                        'company_divison' => $company_divison,
                        'financial_year' => $financial_year,
                        'month' => $months,
                        'invoice_no' => $invoice_no,
                        'customer_name' => $customer_name,
                        'verticle' => $verticle,
                        'bu_l1' => $bu_l1,
                        'bu_l2' => $bu_l2,
                        'type' => $type,
                        'currency' => $currency,
                        'total_billed_hrs' => $total_billed_hrs,
                        'rate_hr' => $rate_hr,
                        'foreign_currency' => $foreign_currency,
                        'exch_rate' => $exch_rate,
                        'amount_in_inr' => $amount_in_inr,
                        'geography' => $geography,
                        'sales_person' => $sales_person,
                        'project_name' => $project_name,
                        'project_id' => $project_id,
                        'inv_to_place' => $inv_to_place,
                        'po' => $po,
                        'offshore_onsite' => $offshore_onsite,
                        'invoice_date' => $invoice_date,
                        'address' => $address,
                        'country' => $country,
                        'softex' => $softex,
                        'status' => '1',
                        'created_by'=>1,
                        'created_date' => date('Y-m-d H:i:s'),
                        'created_ip_address' => $_SERVER['REMOTE_ADDR']
                    );
             
                    $this->Md_login->insertData($table, $insertData);
                   
                }
             $i++;
            }
           
             $final = array('status' => 1, 'msg' =>'Thanks! File Uploaded Successfully.');
            echo json_encode($final);
            exit(); 
        }else {
             $final = array('status' => 2, 'msg' =>'Sorry! File Uploading issue.');
            echo json_encode($final);
            exit(); 
        }
        
        } catch (Exception $e) 
        {
            $final = array('status' => 2, 'msg' =>$e);
            echo json_encode($final);
            exit(); 
        }
    }
    
}
