<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Helpers\CommonHelper;
use App\User;
use App\Http\Controllers\Controller;
use Corcel\Model\Post as WordpressPost;
use App\Models\LogsAPIs;
use App\Models\UserLibrary;

use App\Models\Matters;
use App\Models\MatterInvoices;
use App\Models\ConnectData;
use App\Models\UserMatterFavourites;
use App\Models\UserMatterRequest;
use App\Models\MatterOtp;
use App\Models\MatterUsers;
use App\Models\MatterTrustBalance;
use App\Models\UserDevices;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;




class CronMatterController extends Controller
{
    function allMatterInvoiceCron()
    {
        $compressed_xml = storage_path(env('XML_COMPRESSED_PATH'));
        $zipExtractPath = storage_path(env('XML_FILES_PATH'));

        $zipFile = 'xmfiles.zip';

        if(file_exists($compressed_xml.$zipFile))
        {
            // print_r($compressed_xml);
            $za = new \ZipArchive(); 
            
            $za->open($compressed_xml.$zipFile); 
            $za->setPassword('click123');
            if($za->extractTo($zipExtractPath))
            {
                $this->eliteParseMattersXML();
                $this->eliteParseMattersUsersXML();
                $this->eliteParseMattersTrustBalanceXML();
                $this->eliteParseInvoicesXML();

                $files = glob($zipExtractPath . '/*');
                foreach($files as $f)
                {
                    unlink($f);
                }
                $za->close();
                unlink($compressed_xml.$zipFile);
                echo "DONE";
            }
            else
            {
                echo 'NOT DONE';
            }
        }


        die;

    }
    function eliteParseMattersXML()
    {
        $xmlstring = File::get(storage_path('app/public/3rd-party-files/3e-elite/Matter.xml'));

        $xmlstring = utf8_encode($xmlstring);

        $xmlstring = str_replace('dbo.', 'dbo_', $xmlstring);



        $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);

        //echo '<pre>';
        //print_r($xml);
        //exit;

        $arrData = array();

        if($xml)
        {

            foreach($xml as $_xml_obj)
            {
                
                $dbo_Client         = $_xml_obj->dbo_Client;
                $dbo_Arrangement    = $dbo_Client->dbo_Arrangement;
                $dbo_MattRate       = $dbo_Arrangement->dbo_MattRate;
                $dbo_Address        = $dbo_MattRate->dbo_Address;
                $dbo_Timekeeper     = $dbo_Address->dbo_Timekeeper;

                $dbo_NxFWKUser     = $dbo_Timekeeper->dbo_NxFWKUser;

                $dbo_Department     = $dbo_NxFWKUser->dbo_Department;
                $dbo_Office         = $dbo_Department->dbo_Office;
                $dbo_ATAOLDept      = $dbo_Office->dbo_ATAOLDept;

                //info!
                $matterAppUsers     = 'REMOVED';    //-->$_xml_obj->MatterAppUsers;
                $matterName         = $_xml_obj->MatterName;
                $matterNumber       = $_xml_obj->MatterNumber;
                $clientMatterNumber = $_xml_obj->ClientMatter;
                
                $matterCurrency     = $_xml_obj->MatterCurrency;
                $matterOpenDate     = $_xml_obj->MattOpenDate;
                
                $clientNumber       = $dbo_Client->ClientNumber;
                $clientName         = $dbo_Client->ClientName;
                $matterStatus       = $dbo_Client->MattStatus;
                $currentMonth       = $dbo_Client->CurrentMonth; // 'REMOVED';
                $yearToDate         = $dbo_Client->YearToDate;
                $lifeToDate         = $dbo_Client->LifeToDate;  //REMOVED
                $trustBalance       = 'REMOVED';    //-->$dbo_Client->TRBalance; //Note: Manage from new XML -- DONE
                $totalOutstanding   = $dbo_Client->TotalOutstanding;

                $feeArrangement     = $dbo_Arrangement->FeeArrangement;

                $billingAddress     = $dbo_Address->BillingAddress;

                $billingTKName      = $dbo_Timekeeper->BillingTK;

                $billingTKEmail     = $dbo_NxFWKUser->BTKEmail;

                $department         = $dbo_Department->Department;

                $office             = $dbo_Office->Office;

                $areaOfLaw          = $dbo_ATAOLDept->AreaOfLaw;

                $dataForMatter = array(

                    'matterName'            => CommonHelper::DBEncrypt( (string) $matterName),
                    'matterNumber'          => CommonHelper::DBEncrypt( (string) $matterNumber),
                    'clientMatterNumber'    => CommonHelper::DBEncrypt( (string) $clientMatterNumber), // new field - done
                    'matterCurrency'        => CommonHelper::DBEncrypt( (string) $matterCurrency),
                    'matterOpenDate'        => CommonHelper::DBEncrypt( (string) $matterOpenDate),
                    
                    'clientNumber'          => CommonHelper::DBEncrypt( (string) $clientNumber),
                    'clientName'            => CommonHelper::DBEncrypt( (string) $clientName),        // new field - done
                    'matterStatus'          => CommonHelper::DBEncrypt( (string) $matterStatus),
                    'currentMonth'          => CommonHelper::DBEncrypt( (string) $currentMonth),  // Talha  Delete 
                    'yearToDate'            => CommonHelper::DBEncrypt( (string) $yearToDate),
                    'lifeToDate'            => CommonHelper::DBEncrypt( (string) $lifeToDate),     // Talha  Delete 
                    // 'trustBalance'          => (string) $trustBalance,     // remove - done
                    'totalOutstanding'      => CommonHelper::DBEncrypt( (string) $totalOutstanding),
                    
                    'feeArrangement'        => CommonHelper::DBEncrypt( (string) $feeArrangement),
                    
                    'billingAddress'        => CommonHelper::DBEncrypt( (string) $billingAddress),

                    'billingTKName'         => CommonHelper::DBEncrypt( (string) $billingTKName),

                    'billingTKEmail'        => CommonHelper::DBEncrypt( (string) $billingTKEmail), //new field - done

                    'department'            => CommonHelper::DBEncrypt( (string) $department),

                    'office'                => CommonHelper::DBEncrypt( (string) $office),
                    
                    'areaOfLaw'             => CommonHelper::DBEncrypt( (string) $areaOfLaw),

                    );


                    $arrData[] = $dataForMatter;

                    // Matters::updateOrCreate(['matterNumber' => CommonHelper::DBEncrypt($matterNumber) ], $dataForMatter);

                    $check_matter = Matters::where('matterNumber', CommonHelper::DBEncrypt( $matterNumber) )->count();

                    if($check_matter > 0)
                    {
                        Matters::where('matterNumber', CommonHelper::DBEncrypt( $matterNumber )  )->update($dataForMatter);
                    }else{
                        MatterUsers::create($dataForMatter);
                    }
            }
        }

        // echo '<pre>';
        // print_r($arrData);
        // echo '</pre>';

        echo 'Matters-Imported!';
        // exit;
    }

    function eliteParseMattersUsersXML()
    {
        $xmlstring = File::get(storage_path('app/public/3rd-party-files/3e-elite/MatterUser.xml'));

        $xmlstring = utf8_encode($xmlstring);

        $xmlstring = str_replace('dbo.', 'dbo_', $xmlstring);

        $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);

        $arrData = array();

        if($xml)
        {
            //-->Matters::query()->truncate(); //remove all current records!

            foreach($xml as $_xml_obj)
            {
                $dbo_ATAppUser = $_xml_obj->dbo_ATAppUser;

                foreach($dbo_ATAppUser as $_MatterUserEmail)
                {
                    $MatterNumber = (string) $_xml_obj->MatterNumber;
                    $matterUserEmail = (string) $_MatterUserEmail->UserEmail;

                    $_data = array(
                            'email' => CommonHelper::DBEncrypt( $matterUserEmail ),
                            'matterNumber' => CommonHelper::DBEncrypt( $MatterNumber ),
                    );

                    // MatterUsers::updateOrCreate(['email' => $matterUserEmail], $_data);

                    $check_user_matter = MatterUsers::where('email', CommonHelper::DBEncrypt( $matterUserEmail) )->count();

                    if($check_user_matter > 0)
                    {
                        MatterUsers::where('email', CommonHelper::DBEncrypt( $matterUserEmail )  )->update($_data);
                    }
                    else
                    {

                        MatterUsers::create($_data);

                        // get push notification user
                        $_check_user = array();
                        $_check_user = User::where('email', $matterUserEmail)->first();

                        $device_notification = UserDevices::where('user_id', $_check_user->id)->get();

                        if(!empty($device_notification))
                        {
                            foreach ($device_notification as $device) {
                                if($_check_user->hasRole('client'))
                                {
                                    $value = array('matterNumber' => $MatterNumber);

                                    $notify = array(
                                            'user_id' => $_check_user->id,
                                            'email' => $_check_user->email,
                                            'type' => 'matters',
                                            'value' => json_encode($value),
                                            'heading' => 'Matter #: '.$MatterNumber.' has been added',
                                            'text' => 'Matter added',
                                            'date' => time(),
                                            'device_id' => $device->device_id,
                                            'device_type' => $device->device_type
                                        );

                                    CommonHelper::addNotification(array($notify));

                                }
                            }
                        }
                    }


                }



            }
        }

        echo 'Matters Users -Imported!';
        // exit;
    }

    function eliteParseMattersTrustBalanceXML()
    {
        $xmlstring = File::get(storage_path('app/public/3rd-party-files/3e-elite/TrustBalances.xml'));

        $xmlstring = utf8_encode($xmlstring);

        $xmlstring = str_replace('dbo.', 'dbo_', $xmlstring);

        $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);

        $arrData = array();

        if($xml)
        {
            //-->Matters::query()->truncate(); //remove all current records!

            foreach($xml as $_xml_obj)
            {
                
                $MatterNumber = (string) $_xml_obj->MatterNumber;
                $dbo_MxTrustBalancesTApp = $_xml_obj->dbo_MxTrustBalancesTApp;

                $Currency = (string) $dbo_MxTrustBalancesTApp->Currency;
                $TRBalance = (string) $dbo_MxTrustBalancesTApp->TRBalance;

                $arrData[$MatterNumber] = ['currency' => $Currency, 'TRBalance' => $TRBalance];

                $_data = array(
                    'matterNumber' => CommonHelper::DBEncrypt( $MatterNumber ),
                    'currency' => CommonHelper::DBEncrypt( $Currency ),
                    'trBalance' => CommonHelper::DBEncrypt( $TRBalance )
                );
                MatterTrustBalance::updateOrCreate(['MatterNumber' => CommonHelper::DBEncrypt($MatterNumber)], $_data);

            }
        }
        echo 'Matters Trust Balance -Imported!';
        // exit;
    }

    function eliteParseInvoicesXML()
    {
        $xmlstring = File::get(storage_path('app/public/3rd-party-files/3e-elite/Invoices.xml'));

        $xmlstring = str_replace('dbo.', 'dbo_', $xmlstring);

        $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);

        $arrData = array();

        // echo "<pre>";
        // print_r($xml);
        // die;

        if($xml)
        {
        
                $c = 0;
            foreach($xml as $_xml_obj)
            {
                $c++;
                $dbo_InvMaster      = $_xml_obj->dbo_InvMaster;

                //info!
                $matterNumber       = (string) $_xml_obj->MatterNumber;
                
                $invoiceNumber      = $dbo_InvMaster->InvNumber;
                $invoiceDate        = $dbo_InvMaster->InvDate;
                $dueDate            = $dbo_InvMaster->DueDate;
                $invoiceCurrency    = $dbo_InvMaster->InvCurrency;
                $isPaid             = $dbo_InvMaster->IsPaid;
                $invoiceTotal       = $dbo_InvMaster->InvTotal;
                $balanceAmount      = $dbo_InvMaster->BalAmt;
                $receivedAmount     = $dbo_InvMaster->ReceivedAmt;

                $dataForMatterInvoice = array(

                                    'matterNumber'        => CommonHelper::DBEncrypt( (string) $matterNumber ),

                                    'invoiceNumber'       => CommonHelper::DBEncrypt( (string) $invoiceNumber ),
                                    'invoiceDate'         => ( (string) $invoiceDate ),
                                    'dueDate'             => CommonHelper::DBEncrypt( (string) $dueDate ),
                                    'invoiceCurrency'     => CommonHelper::DBEncrypt( (string) $invoiceCurrency ),
                                    'isPaid'              => CommonHelper::DBEncrypt( (string) $isPaid ),
                                    'invoiceTotal'        => CommonHelper::DBEncrypt( (string) $invoiceTotal ),
                                    'balanceAmount'       => CommonHelper::DBEncrypt( (string) $balanceAmount ),
                                    'receivedAmount'      => CommonHelper::DBEncrypt( (string) $receivedAmount ),
                    );

                // $arrData[$matterNumber][] = $dataForMatterInvoice;

                // delete with respect to matter id
                // table : matter invoices

                // simple data insertion

                // MatterInvoices::updateOrCreate(['matterNumber' => CommonHelper::DBEncrypt($matterNumber), 'invoiceNumber' => CommonHelper::DBEncrypt($invoiceNumber)], $dataForMatterInvoice);

                $check_invoice = 
                MatterInvoices::where('matterNumber', CommonHelper::DBEncrypt($matterNumber))->where( 'invoiceNumber', CommonHelper::DBEncrypt($invoiceNumber) )
                ->count();

                if($check_invoice > 0)
                {
                    MatterInvoices::where( 'matterNumber', CommonHelper::DBEncrypt( $matterNumber ))->where('invoiceNumber', CommonHelper::DBEncrypt($invoiceNumber) )->update($dataForMatterInvoice);
                }else{
                    MatterInvoices::create($dataForMatterInvoice);

                    $matter_users = MatterUsers::where('matterNumber', CommonHelper::DBEncrypt($matterNumber) )->first();
                    if(!empty($matter_users))
                    {
                        if(!empty($matter_users->email))
                        {
                            $_check_user = User::where('email', CommonHelper::DBDecrypt($matter_users->email) )->first();

                            if(!empty($_check_user))
                            {
                                $device_notification = UserDevices::where('user_id', $_check_user->id)->get();

                                if(!empty($device_notification))
                                {
                                    foreach ($device_notification as $device) 
                                    {

                                        if($_check_user->hasRole('client'))
                                        {
                                            $_matter_number = $matterNumber;
                                            $_invoice_number = $invoiceNumber;
                                            $value = array( 'matter_number' => $_matter_number, 'invoiceNumber' => $_invoice_number);

                                            $notify = array(
                                                    'user_id' => $_check_user->id,
                                                    'email' => $_check_user->email,
                                                    'type' => 'invoice',
                                                    'value' => json_encode($value),
                                                    'heading' => 'Invoice #: '.$_invoice_number.' generated',
                                                    'text' => 'New invoice is generated',
                                                    'date' => time(),
                                                    'device_id' => $device->device_id,
                                                    'device_type' => $device->device_type
                                                );

                                            CommonHelper::addNotification(array($notify));
                                        } 
                                    }
                                }
                            }
                        }
                    }
                }
                
            }
        }
        echo 'Matters-Invoices-Imported!';

        // echo '<pre>';
        // print_r($arrData);
        // echo '</pre>';
        // exit;
    }
    function encryptData($string)
    {
        return CommonHelper::DBEncrypt($string);
    }
    function decryptData($string)
    {
        return CommonHelper::DBDecrypt($string);
    }
}