<?php

use App\Classes\Exceptions\InternalServerErrorException;
use App\Classes\Jobs\FetchContainersStatusUpdateFromVTPortalJob;
use App\Classes\Jobs\FetchDeliveryListFromVTPortalJob;
use App\Classes\Jobs\FetchLoadedContainersFromVTPortalJob;
use App\Classes\Jobs\FetchOrdersFromYDPortalJob;
use App\Classes\Jobs\FetchPackingListFromVTPortalJob;
use App\Classes\Jobs\FetchWarehouseReceiveListFromVTPortalJob;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Orders\Processors\UpdateDoFromVTPortalProcessor;
use App\Classes\Modules\Orders\Processors\UpdateDoFromYDPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchOrderListsFromYdPortalProcessor;
use App\Classes\Modules\PackingLists\Processors\FetchPackingListFromVTPortalProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Models\CompanyConnection;
use App\Models\CompanyModule;
use App\Models\Document;
use App\Models\PackingList;
use Illuminate\Support\Facades\Crypt;
use App\Models\Container;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Meneses\LaravelMpdf\Facades\LaravelMpdf;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

require __DIR__ . '/template.php';

Route::domain('hywave.izyim.com')->group(function () {
    Route::group(['as' => 'last_mile_delivery.'], function () {
        Route::get('/', function () {
            return view('pages.accounts.signup');
        })->name('login');

        Route::get('/dashboard', function () {
            return view('pages.delivery.dashboard');
        })->name('dashboard');

        Route::get('/orders/export', 'Delivery\ExportDeliveryOrdersToExcelController@lineClear')->name('order.export');

    });
});

Route::group(['prefix'=> '/last_mile_delivery', 'as' => 'last_mile_delivery.'], function () {
    Route::get('/', function () {
        return view('pages.accounts.signup');
    })->name('login');

    Route::get('/dashboard', function () {
        return view('pages.delivery.dashboard');
    })->name('dashboard');

    Route::get('/orders/export', 'Delivery\ExportDeliveryOrdersToExcelController@lineClear')->name('order.export');

});

Route::group(['prefix'=> '/air_shipment', 'as' => 'air_shipment.'], function () {
    // Route::get('/', function () {
    //     return view('pages.accounts.signup');
    // })->name('login');

    Route::get('/quotation', function () {
        return view('pages.airShipment.quotation');
    })->name('quotation');
});

Route::get('', function () {
    return view('pages.accounts.login');
})->name('login');

Route::get('/signup', function () {
    return view('pages.accounts.sign_up');
})->name('signup');


Route::group(['prefix' => 'swagger'], function () {
    Route::get('/', function () {
        return view('swagger.index');
    });
    Route::get('/json', function () {
        return view('swagger.json');
    });
});

Route::get('/business/claim/{hash}', function ($hash) {
    return view('pages.accounts.claim_business', ['id' => Crypt::decryptString($hash)]);
})->name('company.claim');

Route::get('/account/email/verification/{token}', function ($token) {
    return view('pages.accounts.email_verified', ['token' => $token]);
})->name('account.email.verification');

Route::get('/account/password/reset/{token}', function ($token) {
    return view('pages.accounts.reset_password', ['token' => $token]);
})->name('account.password.reset');

Route::get('/dashboard', function () {
    return view('pages.dashboard');
})->name('dashboard');

Route::get('/customers', function () {
    return view('pages.admin.customers');
})->name('customers');

Route::get('/orders', function () {
    return view('pages.orders.index');
})->name('orders');

Route::get('/orders-table', function () {
    return view('pages.orders.table');
})->name('ordersTable');

Route::get('/order/show/{order_number}', function ($orderNumber) {
    return view('pages.orders.profile', ['id' => $orderNumber]);
})->name('order.show');

Route::get('/address', function () {
    return view('pages.addresses.index');
})->name('address');

Route::get('/warehouse-list', function () {
    return view('pages.warehouse_list');
})->name('warehouse.list');

Route::get('/delivery-list', function () {
    return view('pages.delivery_list');
})->name('delivery.list');

Route::get('/unclaimed-packinglist', function () {
    return view('pages.unclaimed_packinglist');
})->name('unclaimed-packinglist.list');

Route::get('/containers', function () {
    return view('pages.containers');
})->name('containers');

Route::get('/container/show/{reference}', function ($reference) {
    $container = Container::where('reference', $reference)->first();
    return view('pages.templates.warehouseFlow', ['id' => $container->id]);
})->name('container.show');

Route::get('/customer/{marking}', function ($marking) {
    $connection = CompanyConnection::where('invitee_reference', $marking)->first();
    $id = $connection->invitee->company->id;
    return view('pages.customers.profile', ['id' => $id]);
})->name('customer.profile');

Route::get('/customer/{marking}/details', function ($marking) {
    $connection = CompanyConnection::where('invitee_reference', $marking)->first();
    $id = $connection->invitee->company->id;
    return view('pages.customers.profile_details', ['id' => $id]);
})->name('customer.profile.details');

Route::get('/customer/{marking}/payment-and-billing', function ($marking) {
    $connection = CompanyConnection::where('invitee_reference', $marking)->first();
    $company_module_id = $connection->invitee->id;
    return view('pages.customers.paymentsBilling', ['company_module_id' => $company_module_id]);
})->name('customer.payment-and-billing');

Route::get('/orders/refresh', function(\Illuminate\Http\Request $request){
    $packingLists = \App\Models\PackingList::where('type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->has('containers')->get();
    dd($packingLists);
    $packingLists->each(function (\App\Models\PackingList $packingList) {
        $packingList->containers()->detach();
    });
    FetchWarehouseReceiveListFromVTPortalJob::withChain([
        new FetchLoadedContainersFromVTPortalJob,
        new FetchOrdersFromYDPortalJob
    ])->dispatch();

    return redirect('orders');

})->name('orders.refresh');

Route::get('/containers/refresh', function(){

    dd((App()->make(\App\Classes\Modules\PackingLists\Processors\FetchLoadedContainersFromVTPortalProcessor::class))->execute());
//    FetchLoadedContainersFromVTPortalJob::dispatch();
//    FetchContainersStatusUpdateFromVTPortalJob::dispatch();

    return redirect('orders');

})->name('containers.refresh');

Route::get('/deliveries/refresh', function(){

    FetchDeliveryListFromVTPortalJob::dispatch();

    return redirect('orders');

})->name('deliveries.refresh');

Route::get('/order/{id}/download', 'Orders\DownloadOrderQrPdfController@download')->name('order.qr.download');

Route::get('/report/customclearance/{orderid}', 'Reports\CustomcClearanceReportController@download')->name('report.customclearance');

Route::group(['prefix' => 'template', 'as' => 'template.'], function () {
    Route::get('/payment-and-billing', function () {
        return view('pages.templates.paymentsBilling');
    })->name('payment-and-billing');

    Route::get('/shipping-queue', function () {
        return view('pages.templates.shippingQueue');
    })->name('shipping-queue');
});

Route::get('/yiwu', function () {
    $orders = \App\Models\Order::whereHas('OrderRoles', function($query){
        return $query->where('role_id', \App\Classes\ValueObjects\Constants\OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 2358);
    })->get();

    foreach ($orders as $order){
        echo '<a target="_blank" href="'.route('order.show', $order->reference).'">'. $order->reference.' - '.$order->created_at.'</a><br>';
    }

});

Route::get('/guangzhou', function () {
    $orders = \App\Models\Order::whereHas('OrderRoles', function($query){
        return $query->where('role_id', \App\Classes\ValueObjects\Constants\OrderRoleTypes::ORIGIN_WAREHOUSE)->where('company_module_id', 3);
    })->whereHas('addresses', function($query){
        return $query->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->whereIn('state_id', [5, 13, 14]);
    })->get();

    foreach ($orders as $order){
        echo '<a target="_blank" href="'.route('order.show', $order->reference).'">'. $order->reference.' - '.$order->created_at.'</a><br>';
    }

});

Route::get('/debug', function (){
    $orders = \App\Models\Order::all();

    $issues = [];
    foreach ($orders as $order){
        $received = $order->parcels()->warehouseReceiveList()->sum('quantity');
        $shipping = $order->parcels()->shippingList()->sum('quantity');
        if( $received < $shipping){
            $issues[] = [
                'order' => $order->reference,
                'received' => $received,
                'shipping' => $shipping
            ];
        }
    }

    dd($issues);
});

Route::get('/yd', function (\Illuminate\Http\Request $request){
    $start = $request->input('start_date') ? \Carbon\Carbon::parse($request->input('start_date')): null;
    $end = $request->input('end_date') ? \Carbon\Carbon::parse($request->input('end_date')): null;
    (App()->make(FetchOrderListsFromYdPortalProcessor::class))->execute($start, $end);
    (App()->make(FetchPackingListFromVTPortalProcessor::class))->execute();
})->name('yd.refresh');

Route::get('/container/{reference}/refresh/', function (string $reference){
    $container = Container::where('reference', $reference)->first();
    $supplier = in_array($container->owner_id, [3, 4]) ? 'VT' : 'YD';

    $arrivalDates = \App\Models\PackingList::whereIn('reference', $container->packingLists->pluck('reference'))->where('type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->get()->map(function($packingList){
        return $packingList->transports()->first()->drop_date;
    })->sortBy(function($date){
        return $date;
    });

    $startDate = $arrivalDates->first()->subDay()->format('d-m-Y');
    $endDate = $arrivalDates->last()->addDay()->format('d-m-Y');

    if($supplier === 'VT'){
        return (App()->make(\App\Classes\Modules\PackingLists\Processors\FetchLoadedContainersFromVTPortalProcessor::class))->execute(\Carbon\Carbon::parse($endDate), \Carbon\Carbon::parse($endDate)->addDays(5));
    }

    if($supplier === 'YD'){
        return redirect(route('yd.refresh').'?start_date='.$startDate.'&end_date='.$endDate);
    }

})->name('container.refresh');

Route::get('/min_cbm', function (){
    $companies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orders', function ($query){
        return $query->whereHas('packingLists')->whereDoesntHave('packingLists', function($query){
            return $query->whereHas('packages', function($query){
                return $query->selectRaw('sum((width/100) * (height/100) * (length/100) * quantity) as cbm')->where('type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->where('status', '!=', 5)->having('cbm', '>', 0.3);
            });
        });
    })->limit(1)->get();

    $i = 0;
    foreach ($companies as $company) {
        $marking = $company->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
        echo '<a href="'.route('customer.profile', $marking).'" target="_blank">'.$i++.'. '.$marking.'</a><br>';
    }
});

Route::get('/warehouse', function () {
    return view('pages.warehouse');
})->name('warehouse');

Route::get('/warehouse/{id}/show', function ($id) {
    // $connection = CompanyConnection::where('invitee_reference', '2417MEN')->first();
    // $id = $connection->invitee->company->id;
    return view('pages.templates.warehouseDetails', ['id' => $id]);
})->name('warehouse.show');
Route::get('/export/customer-latest-order-date/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@export');
Route::get('/export/packing-list/{id}', 'Exports\ExportContainerPackingListController@export')->name('container.packaging_list.export');
Route::get('/export/pending-arrangement-delivery-list', 'Exports\ExportPendingArrangementPackingListController@export')->name('packaging_list.pending_arrangement.export');
Route::get('/export/on-hold-packing-list', 'Exports\ExportPendingArrangementPackingListController@onHold')->name('packaging_list.on_hold.export');
Route::get('/export/arrived-parcel', 'Exports\ExportArrivedParcelController@export')->name('packing_list.arrived_parcel.export');
Route::get('/export/parcel-summary', 'Exports\ExportArrivedParcelController@summary');
Route::get('/export/parcel-postcode', 'Exports\ExportParcelPostcodesController@export');
Route::get('/export/{year}/customer-total-order', 'Exports\ExportCustomersToExcelController@totalOrders');
Route::get('/export/packing-list-warehouse/guangzhou2-to-johor', 'Exports\ExportArrivedParcelController@guangZhou2ToJohor');

Route::get('/settings', function () {
    return view('pages.settings');
})->name('settings');
Route::get('/settings', function () {
    return view('pages.settings');
})->name('settings');

Route::get('/customer/{company_module_id}/summary', 'Exports\ExportCompanyModuleSummaryController@export')->name('customer.summary.export');

Route::get('/customer/summary/monthly', function () {
    $containers = Container::whereMonth('loading_date', '>=', ((float)\Carbon\Carbon::now()->format('m') - 2))->whereYear('loading_date', (float)\Carbon\Carbon::now()->format('Y'))->get();
    foreach ($containers as $container){
        $packingLists = $container->packingLists()->get()->filter(function ($packingList) {
            return $packingList->owner->company_module_id === 248;
        });

        if (!count($packingLists)) continue;

        echo '<table style="width: 100%; text-align: center;">
          <tr>
            <th>Date</th>
            <th>Full Marking</th>
            <th>Container</th>
            <th>Description</th>
            <th>Ctns</th>
            <th>L (cm)</th>
            <th>H (cm)</th>
            <th>W (cm)</th>
            <th>CBM</th>
          </tr>';
        foreach ($packingLists as $packingList){
            if($packingList->packingLists->first()){
                $packingList = $packingList->packingLists->first();
            }
            $packages = $packingList->packages;
            foreach ($packages as $package){
                echo '<tr>
                        <td>'.$container->loading_date->format('d-m-Y').'</td>
                        <td>MS/CIEF/769SMC/'.$packingList->owner->reference.'</td>
                        <td>'.$container->reference.'</td>
                        <td>'.$package->description.'</td>
                        <td>'.$package->quantity.'</td>
                        <td>'.$package->length.'</td>
                        <td>'.$package->height.'</td>
                        <td>'.$package->width.'</td>
                        <td>'.((($package->length / 100) * ($package->height / 100) * ($package->width / 100)) *  $package->quantity).'</td>
                      </tr>';
            }
        }
        echo '</table>';


    }

});

Route::get('/customers/active/{active_start}/{active_end}/{inactive_start?}/{inactive_end?}/{with_cbm?}', function ($active_start, $active_end, $inactive_start=null, $inactive_end=null, $with_cbm = false) {
    $activeCompanies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($inactive_start, $inactive_end) {
        return $query->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($inactive_start, $inactive_end) {
            return $query->where('drop_date', '>=', \Carbon\Carbon::parse($inactive_start))->where('drop_date', '<=', \Carbon\Carbon::parse($inactive_end)->addDay());
        });
    })->pluck('id');

    $companies = CompanyModule::where('type', \App\Classes\ValueObjects\Constants\BusinessType::IMPORTER)->whereHas('orderPackingLists', function($query) use($active_start, $active_end) {
        return $query->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::WAREHOUSE_RECEIVE_LIST)->whereHas('transports', function ($query) use ($active_start, $active_end) {
            return $query->whereDate('drop_date', '>=', \Carbon\Carbon::parse($active_start))->whereDate('drop_date', '<=', \Carbon\Carbon::parse($active_end)->addDay());
        });
    })->whereNotIn('id', $activeCompanies)->get();

    echo '<h4>List of customers active between <span style="color: green; font-weight: bold">'.\Carbon\Carbon::parse($active_start)->format('d/m/Y'). ' - '.\Carbon\Carbon::parse($active_end)->format('d/m/Y').'</span> & inactive between <span style="color: red; font-weight: bold">'.\Carbon\Carbon::parse($inactive_start)->format('d/m/Y'). ' - '.\Carbon\Carbon::parse($inactive_end)->format('d/m/Y').'</span></h4>';
    echo '<table>
          <tr>
            <th>#</th>
            <th>marking</th>
            <th>Number of Orders</th>
            <th>CBM</th>
          </tr>';
    foreach ($companies as $key => $company){
        $connection = $company->inviters()->withPivot('invitee_reference')->first();
        $marking = $connection ? $connection->pivot->invitee_reference:'';
        $packingList = collect();
        $totalCbm = 0;
        if($with_cbm){
            $packingList = $company->orderPackingLists()->where('packing_lists.type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->get();
            $totalCbm = $packingList->flatMap(function ($packingList) {
                return $packingList->packages;
            })->sum(function($package){
                return (( (float) $package->width / 100) * ( (float) $package->length / 100) * ( (float) $package->height / 100)) * $package->quantity;
            });
        }

        echo '<tr>
                        <td>'.$key.'</td>
                        <td><a href="'.route('customer.profile', $marking).'" target="_blank">'.$marking.'</a></td>
                        <td>'. $packingList->count() .'</td>
                        <td>'. $totalCbm .'</td>
                      </tr>';
    }
    echo '</table>';

});

Route::get('/online_payment/redirect', 'Billplz\CallbackBillplzController@callback')->name('online_payment.redirect');

Route::get('/order/{id}', function ($id) {
    return view('pages.orders.profile', ['id' => $id]);
})->name('order.details');

Route::get('/payment-and-billing', function () {
    return view('pages.paymentAndBilling');
})->name('admin.payment-and-billing');
Route::get('/notifications/list', 'Notifications\ListNotificationsController@list')->name('notifications.list');

Route::get('billplz/bills/{bill_no}', function($bill_no){
    return redirect(env('BILLPLZ_BASE_URL').'/bills/'.$bill_no);
 })->name('billplz.bill');

Route::get('/export/null-debtor/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@nullDebtor')->name('newDebtor.export');
Route::get('/export/payment-transactions/f614e339d7058904a831aad742e24d55', 'Exports\ExportCustomersToExcelController@paymentTransactions')->name('paymentTransactions.export');

Route::get('/delayed_container/customers', function(){
    $containers = Container::whereHas('transports', function($query){
        return $query->whereHas('Schedules', function($query){
            return $query->where('etd', '>', \Carbon\Carbon::parse('15-10-2022'));
        });
    })->get();

    $orders = $containers->map(function($container){
        return $container->orders;
    })->flatten()->unique(function($order){
        return $order->company_module_id;
    });

    $companies = CompanyModule::whereIn('id', $orders->pluck('company_module_id'))->get();

    foreach ($companies as $company){
        $marking = $company->inviters()->withPivot('invitee_reference')->first()->pivot->invitee_reference;
        echo '<a target="_blank" href="'.route('customer.profile', $marking).'">'.$marking.'</a><br>';
    }


});


Route::get('/container/billing/{month}/{year}', function($month, $year){
    $containers = Container::whereDate('loading_date', '>=', \Carbon\Carbon::parse('01-'.$month.'-'.$year))->whereDate('loading_date', '<', \Carbon\Carbon::parse('01-'.$month.'-'.$year)->addMonth())->get();

    $totalBillable = 0;
    $billed = 0;
    $totalBilled = 0;
    $totalPaid = 0;

    $basePrice = 315;
    $bigParcelDiscount = -15;

    $yiwuCost = 15;

    $discount = -20;
    $yiwuDiscount = -45;

    $outstationStates = [8, 3, 16, 10];


    foreach($containers as $container) {
        $containerTotalBillable = 0;
        $containerBilled = 0;
        $containerTotalBilled = 0;
        $containerTotalPaid = 0;
        $containerCost = 0;

        $packingLists = $container->packingLists;

        $totalBillable += count($packingLists);
        $containerTotalBillable += count($packingLists);
        echo '<h3>'.$container->reference.' ('.$container->loading_date->format('d-m-Y').')</h3>';

        foreach ($packingLists as $packingList) {
            $invoice = $packingList->transactions()
                ->where('type', \App\Classes\ValueObjects\Constants\TransactionType::SHIPPING_INVOICE)->whereIn('status', [\App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED, \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED])
                ->first();


            $warehouseList = PackingList::where('reference', $packingList->reference)->where('type', 1)->first();
            if($warehouseList){
                $packing_list_drop_date = $warehouseList->transports->first()->drop_date;
            } else {
                echo '<------------- can\'t find arrival date -------------->';
            }

            $order = $packingList->owner;
            $address = $order->addresses()->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->first();
            $warehouseId = $order->orderRoles()->where('role_id', OrderRoleTypes::ORIGIN_WAREHOUSE)->first()->company_module_id;

            $cbm = round($packingList->packages->where('type', '!=', PackageType::OVER_WEIGHT)->sum(function($package) {
                return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
            }), 2);

            $over_weight_cbm = round($packingList->packages->where('type', PackageType::OVER_WEIGHT)->sum(function($package) {
                return ($package->width / 100) * ($package->height / 100) *($package->length / 100) * ($package->quantity);
            }), 2);
            $price = $basePrice;

            if($warehouseId === 2358){
                $price += $yiwuCost;
                if($packing_list_drop_date >= \Carbon\Carbon::parse('19-9-2022')){
                    $price += $yiwuDiscount;
                }
            } else {
                if($cbm >= 2 && in_array($address->state_id, [4, 15])){
                    $price += $bigParcelDiscount;
                }
                if($packing_list_drop_date >= \Carbon\Carbon::parse('19-9-2022')){
                    $price += $discount;
                }
            }

            if(in_array($address->state_id,$outstationStates)) {
                $price += 50;
            }

            $cbm = max($cbm, 0.3);
            $cost = $price * ($cbm + $over_weight_cbm);

            $containerCost += $cost;

            if(in_array($address->state_id, [13, 14])) {
                echo 'East Malaysia - ';
            }
            echo 'estimated cost: [QTY: '.($cbm + $over_weight_cbm).' | Unit Price: '.$price.' | Total: '.$cost.']';
            echo '<br>';

            if(!$invoice) {
                echo '<p style="color: red"><a href="'.route('order.show', $order->reference).'" target="_blank">'.$packingList->reference .'</a> Warning: no billing</p>';
                continue;
            }

            $payments = $invoice->transactions()
                ->where('type', \App\Classes\ValueObjects\Constants\TransactionType::PAYMENT)->whereIn('status', [\App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED, \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED])
                ->get();

            $billed += 1;
            $containerBilled += 1;

            $totalBilled += $invoice->amount;
            $containerTotalBilled += $invoice->amount;

            $totalPaid += $payments->sum('amount');
            $containerTotalPaid += $payments->sum('amount');

            echo '<span style="color: '.(($invoice->amount - $payments->sum('amount')) < 0.01 ? 'green' : 'red').'"><p style="color: red"><a href="'.route('order.show', $order->reference).'" target="_blank">'.$packingList->reference .'</a> | Amount: '.$invoice->amount.' | Paid: '.$payments->sum('amount').' | Invoice Date: '.$invoice->created_at->format('d-m-Y'). (($invoice->amount - $payments->sum('amount')) < 0.01 ? '' : '('.$invoice->created_at->diffForHumans().')').'</span>';
            echo '<br><br>';

        }

        echo '<h4>Container Invoices: '.$containerBilled.'/'.$containerTotalBillable.'</h4>';
        echo '<h4>Billed Total: '.$containerTotalBilled.'</h4>';
        echo '<h4>Total Paid: '.$containerTotalPaid.'</h4>';
        echo '<h4>Outstanding: '.($totalBilled - $containerTotalPaid).'</h4>';
        echo '<h4>Estimated Cost: '.$containerCost.'</h4>';
        echo '<br><br><br>';
    }

    echo '<h2>Total Invoices: '.$billed.'/'.$totalBillable.'</h2>';
    echo '<h2>Billed Total: '.$totalBilled.'</h2>';
    echo '<h2>Total Paid: '.$totalPaid.'</h2>';
    echo '<h2>Outstanding: '.($totalBilled - $totalPaid).'</h2>';

});

Route::get('/yd/fix', function(){
    $packingLists = \App\Models\PackingList::where('type', \App\Classes\ValueObjects\Constants\PackingListType::SHIPPING_PACKING_LIST)->where('status', \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED)->where('claimant_id', 2307)->get();
    $i = 0;
    echo count($packingLists).'<br><br>';
    foreach ($packingLists as $packingList){
        try {
            (App()->make(UpdateDoFromYDPortalProcessor::class))->execute($packingList);
            echo 'success'.'<br>';
        } catch (\Exception $exception){
            echo '<span style="color:red;">'.$packingList->reference.'</span>';
        }

    }
});

Route::get('/billplz/fix', function(){
    $payments = \App\Models\Transaction::where('type', \App\Classes\ValueObjects\Constants\TransactionType::PAYMENT)->where('payment_method',\App\Classes\ValueObjects\Constants\PaymentMethodType::PAYMENT_GATEWAY)->get();
    echo '<h3>fixed orders</h3>';
    foreach ($payments as $payment){
        $response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$payment->payment_reference);

        if($response->successful()){
            $data = $response->json();
            $invoice = $payment->owner;
            if(!$invoice){
                continue;
            }
            $packingList = $invoice->owner;
            $order  = $packingList->owner;

            $orderNumber = $order->reference;
            if(!$data['paid'] && $payment->status === \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED) {
                echo '<br><span style="color: red">Fraude: <a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a></span><br>';
                continue;
            }

            if($data['paid']){
                if($payment->status !== \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED){
                    echo '<a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a><br>';
                }
                $payment->status = \App\Classes\ValueObjects\Constants\ApprovalStatus::APPROVED;
                $payment->save();

                $invoice->status = \App\Classes\ValueObjects\Constants\ApprovalStatus::COMPLETED;
                $invoice->save();

                $packingList = $payment->owner->owner;
                if(app()->environment('production')){
                    try {
                        (App()->make(UpdateDoFromVTPortalProcessor::class))->execute($packingList);
                        (App()->make(UpdateDoFromYDPortalProcessor::class))->execute($packingList);
                    } catch (\Exception $exception){
                        echo '<br><span style="color: red">Malformed Address: <a href="'.route('order.show', $orderNumber).'" target="_blank">'.$orderNumber.'</a></span><br>';
                    }
                }
            }
        }else{
           echo "billplz error";
        }

    }
});


Route::get('/invoices/fix', function(){

    $orders = \App\Models\Order::whereIn('company_module_id', [294, 2703])->get();

    foreach ($orders as $order){
        $invoices = $order->transactions()->where('transactions.type', \App\Classes\ValueObjects\Constants\TransactionType::SHIPPING_INVOICE)->get();
        foreach ($invoices as $invoice){

            $invoice->documents()->delete();

            $transaction_invoice_pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoice', ['invoice_transaction' => $invoice]);

            $document_object = new DocumentObject(
                DocumentType::SHIPPING_INVOICE,
                [chunk_split('data:application/pdf;base64,'.base64_encode($transaction_invoice_pdf->output()))],
                '',
                ApprovalStatus::COMPLETED,
                'shipping_invoice'
            );

            /** @var Document $document */
            $document = (App()->make(\App\Classes\Modules\Documents\Services\CreatesDocument::class))->execute($invoice, $document_object);

            (App()->make(\App\Classes\Modules\Documents\Services\CreatesFiles::class))->execute($document, $document_object);
        }
    }

});

Route::get('/invoices/combine/{ids}', function($ids){

    $ids = json_decode($ids);

    $transactions = Transaction::whereIn('id', $ids)->get();

    $pdf = LaravelMpdf::loadView('pages.pdfs.shipping_invoices_combined', ['invoice_transactions' => $transactions]);
    return $pdf->download('combined_invoice_.pdf');
})->name('invoice.combined_summary');


