<?php

namespace App\Listeners\Company;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

use App\Models\ConxOutboundPayment;
use App\Models\LoanBorrowList;
use App\Models\Notifications;
use App\Models\Tasks;
use App\Events\Company\PusherNotificationEvent as CompanyNotificationEvent;
use App\Events\Company\InvoiceUpdateEvent;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Jobs\Company\ProcessSendInvoicePaymentToBorrower;

class InvoiceUpdateNotificationListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(InvoiceUpdateEvent $event)
    {
        if ($event->transaction == "invoice") {

            $LBL = LoanBorrowList::select(
                'loan_borrow_lists.id',
                'search.worker_company_id as worker_id',
                'loan_borrow_lists.loaner_company_id as loaner_id',
                'loan_borrow_lists.borrower_company_id as borrower_id',
                'loan_borrow_lists.status as status',
                'loan_borrow_lists.date_from as date_from',
                'loan_borrow_lists.date_to as date_to'
            )
                ->join('search', 'loan_borrow_lists.worker_id', 'search.worker_id')
                ->where('loan_borrow_lists.id', $event->reference_id)
                ->first();

            switch ($event->action) {
                case 'create':
                    $loaner = [
                        "type" => "Loan Invoice",
                        "company_id" => $LBL->loaner_id,
                        "link" => '/company/loan/billing-invoice',
                        "message" => 'You have sent an invoice for Employee <b>' . $LBL->worker_id . '</b> on <b>' . Carbon::parse($LBL->date_from)->format('F d Y') . '</b> to <b>' . Carbon::parse($LBL->date_to)->format('F d Y') . '</b>. ',
                        "is_read" => 0,
                    ];

                    $borrower = [
                        'type' => "borrow_invoice",
                        'company_id' => $LBL->borrower_id,
                        'link' => "/company/borrow/billing-invoice",
                        'reference_id' => $LBL->id,
                        'message' => 'A company has sent invoice for <b>' . $LBL->worker_id . '</b> on <b>' . Carbon::parse($LBL->date_from)->format('F d Y') . '</b> to <b>' . Carbon::parse($LBL->date_to)->format('F d Y') . '</b>.',
                        'is_read' => false,
                        'status' => 'pending',
                    ];

                    // Log::channel('background')->info("Updated => Billing invoice data:" . $LBL);
                    Tasks::create($borrower);
                    Notifications::create($loaner);
                    event(new CompanyNotificationEvent($loaner)); //Event for realtime notif
                    event(new CompanyNotificationEvent($borrower)); //Event for realtime notif

                    //Notification for company rate

                    break;
                case 'approve':

                    $borrower = [
                        "type" => "Loan Invoice",
                        "company_id" => $LBL->borrower_id,
                        "link" => '/company/borrow/financials',
                        "message" => 'You have approved an invoice for Employee <b>' . $LBL->worker_id . '</b> on <b>' . Carbon::parse($LBL->date_from)->format('F d Y') . '</b> to <b>' . Carbon::parse($LBL->date_to)->format('F d Y') . '</b>. ',
                        "is_read" => 0,
                    ];

                    $loaner = [
                        'type' => "loan_invoice",
                        'company_id' => $LBL->loaner_id,
                        'link' => "/company/loan/financials",
                        'reference_id' => $LBL->id,
                        'message' => 'A company has approved the invoice for <b>' . $LBL->worker_id . '</b> on <b>' . Carbon::parse($LBL->date_from)->format('F d Y') . '</b> to <b>' . Carbon::parse($LBL->date_to)->format('F d Y') . '</b>.',
                        'is_read' => false,
                        'status' => 'pending',
                    ];

                    Tasks::create($loaner);
                    Notifications::create($borrower);
                    event(new CompanyNotificationEvent($loaner)); //Event for realtime notif
                    event(new CompanyNotificationEvent($borrower)); //Event for realtime notif
                    break;
            }

        } elseif ($event->transaction == 'outbound_payment') {
            $transction_details = ConxOutboundPayment::select(
                'loan_borrow_lists.id',
                'loan_borrow_lists.loaner_company_id as loaner_id',
                'loan_borrow_lists.borrower_company_id as borrower_id',
                'loan_borrow_lists.invoice_no',
                'loaner.name as loaner_name',
                'loaner.email_address as loaner_email',
                'borrower.name as borrower_name',
                'borrower.email_address as borrower_email',
                'conx_outbound_payments.amount',
                'search.worker_company_id as worker_id',
            )
                ->join('outbound_billing_requests', 'outbound_billing_requests.id', 'conx_outbound_payments.outbound_billing_request_id')
                ->join('loan_borrow_lists', 'loan_borrow_lists.id', 'outbound_billing_requests.loan_borrow_lists_id')
                ->join('search', 'loan_borrow_lists.worker_id', 'search.worker_id')
                ->join('companies as loaner', 'loaner.id', 'loan_borrow_lists.loaner_company_id')
                ->join('companies as borrower', 'borrower.id', 'loan_borrow_lists.borrower_company_id')
                ->where('conx_outbound_payments.id', $event->reference_id)
                ->first();

            $loaner_mail = [
                "transaction_id" => $transction_details->id,
                "email" => $transction_details->loaner_email,
                "company_name" => $transction_details->loaner_name,
                "invoice_no" => $transction_details->invoice_no,
            ];
            $borrower_mail = [
                "transaction_id" => $transction_details->id,
                "email" => $transction_details->borrower_email,
                "company_name" => $transction_details->borrower_name,
                "invoice_no" => $transction_details->invoice_no,
            ];

            switch ($event->action) {
                case 'Full-Payment':

                    $borrower = [
                        "type" => "Loan Invoice",
                        "company_id" => $transction_details->borrower_id,
                        "link" => '/company/borrow/financials?pid=' . $transction_details->id,
                        "message" => 'Your payment for invoice: <b>' . $transction_details->invoice_no . '</b> has been disbursed to the loaning company of Employee <b>' . $transction_details->worker_id . '</b>. ',
                        "is_read" => 0,
                    ];
                    $loaner = [
                        'type' => "Loan Invoice",
                        'company_id' => $transction_details->loaner_id,
                        'link' => "/company/loan/financials?pid=" . $transction_details->id,
                        'message' => 'You have been paid for invoice: <b>' . $transction_details->invoice_no . '</b> by the borrowing company that borrowed Employee <b>' . $transction_details->worker_id . '</b>.',
                        'is_read' => false,

                    ];
                    Notifications::create($loaner);
                    ProcessSendInvoicePaymentToBorrower::dispatch($loaner_mail)->onConnection('jobs_emails')->onQueue('sendemail');
                    Notifications::create($borrower);
                    event(new CompanyNotificationEvent($loaner)); //Event for realtime notif
                    event(new CompanyNotificationEvent($borrower)); //Event for realtime notif


                    //notfication for rating a transaction here
                    $messageToLoaner = 'The transaction with invoice <b>'. $transction_details->invoice_no .'</b> has been successfully ended. Please rate the service quality of the company that borrowed the Employee <b>' . $transction_details->worker_id .'</b>.';
                    $ratenotificationForLoaner = [
                        'type' => 'Employee',
                        'company_id' => $transction_details->loaner_id,
                        'message' => $messageToLoaner,
                        'link' => "/company/loan/financials?rate=". $transction_details->id,
                        "is_read" => false,
                    ];
                    Notifications::create($ratenotificationForLoaner);
                    event(new CompanyNotificationEvent($ratenotificationForLoaner)); //Event for realtime notif
                    
                    $messageToBorrower = 'The transaction with invoice <b>'. $transction_details->invoice_no .'</b> has been successfully ended. Please rate the service quality of the company that loaned the Employee <b>' . $transction_details->worker_id .'</b>.';
                    $ratenotificationForBorrower = [
                        'type' => 'Employee',
                        'company_id' => $transction_details->borrower_id,
                        'message' => $messageToBorrower,
                        "link" => "/company/borrow/financials?rate=". $transction_details->id,
                        "is_read" => false,
                    ];
                    Notifications::create($ratenotificationForBorrower);
                    event(new CompanyNotificationEvent($ratenotificationForBorrower)); //Event for realtime notif
                    break;

                case 'Partial':

                    $borrower = [
                        "type" => "Loan Invoice",
                        "company_id" => $transction_details->borrower_id,
                        "link" => '/company/borrow/financials?pid=' . $transction_details->id,
                        "message" => 'Your partial payment for for invoice : <b>' . $transction_details->invoice_no . '</b> has been disbursed to the loaning company of Employee <b>' . $transction_details->worker_id . '</b>. ',
                        "is_read" => 0,
                    ];

                    $loaner = [
                        'type' => "Loan Invoice",
                        'company_id' => $transction_details->loaner_id,
                        'link' => "/company/loan/financials?pid=" . $transction_details->id,
                        'message' => 'You have been partially paid for invoice : <b>' . $transction_details->invoice_no . '</b> by the borrowing company that borrowed Employee <b>' . $transction_details->worker_id . '</b>.',
                        'is_read' => false,

                    ];

                    Notifications::create($loaner);
                    Notifications::create($borrower);
                    event(new CompanyNotificationEvent($loaner)); //Event for realtime notif
                    event(new CompanyNotificationEvent($borrower)); //Event for realtime notif

                    break;
            }
        }
    }
}
