<?php

use App\Http\Controllers\Billplz\CallbackBillplzController;
use App\Classes\General\LogHelper;
use App\Http\Controllers\Accounting\BankStatementController;
use App\Http\Controllers\Bookings\AutoPurchaseOrderFillController;
use App\Http\Controllers\Bookings\DownloadBookingDocumentController;
use App\Http\Controllers\Exports\ExportAnalyticToExcelController;
use App\Http\Controllers\Exports\ExportCustomersToExcelController;
use App\Http\Controllers\Exports\ExportCustomersWalletTransactionToExcelController;
use App\Http\Controllers\Imports\ImportBankRecordController;
use App\Http\Controllers\Notifications\ListNotificationsController;
use App\Http\Controllers\Transactions\DownloadMockUpWhiteFormPdfController;
use App\Http\Controllers\Transactions\GenerateCreditNotePdfController;
use App\Models\Group;
use App\Models\Remark;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Booking;
use App\Models\Company;
use App\Models\Transaction;
use Dompdf\Dompdf;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Excel;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use Spatie\Activitylog\Models\Activity;
use Webklex\PDFMerger\Facades\PDFMergerFacade as PDFMerger;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Bookings\Processors\CreatePurchaseOrderFor1688OrderProcessor;
use App\Classes\Modules\Bookings\Services\CalculatesBookingRefundAmount;
use App\Classes\Modules\Documents\Services\DeletesDocument;
use App\Classes\Modules\Transactions\Services\DeletesTransaction;
use App\Classes\Modules\Transactions\ControllersLogic\DownloadMockUpWhiteFormPdfLogic;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionV2Processor;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Classes\General\AWSS3Helper;
use App\Classes\ValueObjects\Constants\KVPKey;
use App\Http\Controllers\Reports\UnfinishedPaymentOrders;
use App\Models\KeyValuePair;
use Illuminate\Support\Facades\File;


/*
|--------------------------------------------------------------------------
| 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!
|
*/

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

Route::get('/signup', function () {
    return view('pages.accounts.sign_up');
})->middleware([
    \App\Http\Middleware\TrackAffiliateClick::class,
    'guest:web'
])->name('signup');

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.dashboards.index');
})->name('dashboard');

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


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

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

Route::get('/customer/{marking}', function ($marking) {
    $id = \App\Models\Company::where('reference', '=', $marking)->first()->id;
    return view('pages.customers.profile', ['id' => $id]);
})->name('customer.profile');

Route::get('/customer/{marking}/transactions', function ($marking) {
    $id = \App\Models\Company::where('reference', '=', $marking)->first()->id;
    return view('pages.transactions.history', ['id' => $id]);
})->name('account.statment');

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

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

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

/* Vue Polling Experiment - Starts  */
Route::get('/billings-experiment', function () {
    return view('pages.billings_experiment');
})->name('billings.experiment');
/* Vue Polling Experiment - Ends  */

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

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

Route::get('/list-transfer', function () {
    return view('pages.bookings.filter');
})->name('list_transfer');

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

Route::get('/transfer/{marking}', function ($marking) {
    return view('pages.bookings.profile', ['marking' => $marking]);
})->name('booking.details');

Route::get('/transfer/{marking}/latest/{document_type}', function ($marking, $document_type) {
    $booking= Booking::where('marking', $marking)->first();

    $purchaseOrder = $booking->transactions()
    ->where('type', TransactionType::PURCHASE_ORDER)
    ->complete()
    ->first();

    $transaction = $booking->transactions()
    ->where('type', TransactionType::PAYMENT)
    ->latest()->get()[0];

    $supplier = Company::where('id', $transaction->receiver)->first();

    $lowercaseDocumentType = null;
    switch  ($document_type) {
        case 'po':
            $lowercaseDocumentType = DocumentType::PURCHASE_ORDER;
            break;
        case 'do':
            $lowercaseDocumentType = DocumentType::DELIVER_ORDER;
            break;
        case 'sdo':
            $lowercaseDocumentType = DocumentType::SUPPLIER_DELIVER_ORDER;
            break;
        default:
            $lowercaseDocumentType = DocumentType::INVOICE;
            break;
    }

    $lowercaseDocumentType = strtolower($lowercaseDocumentType);

    $voucherRedemption = $transaction->voucherRedemption;

    return view('pages.pdfs.' . $lowercaseDocumentType, ['transaction' => $transaction, 'po_order_transaction' => $purchaseOrder, 'supplier' => $supplier, 'voucher_redemption' => $voucherRedemption]);
})->name('booking.details.latest_invoice');

Route::get('/transfer/{marking}/preview-proforma-invoice', function ($marking) {
    $booking= Booking::where('marking', $marking)->first();

    $transaction = $booking->transactions()
        ->where('type', TransactionType::PAYMENT)
        ->first();

    $po_order_transaction = $booking->transactions()
        ->where('type', TransactionType::PURCHASE_ORDER)
        ->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])
        ->first();

    $proforma_transaction = $booking->transactions()->where('type', TransactionType::PROFORMA)->first();

    $supplier = Company::find($transaction->receiver);

    return view('pages.pdfs.proforma_invoice', ['invoice_transaction' => $proforma_transaction, 'po_order_transaction' => $po_order_transaction, 'supplier' => $supplier]);
});

Route::get('/transfer/merge/{marking}', function ($marking) {
    return view('pages.bookings.merge', ['marking' => $marking]);
})->name('booking.merge');

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

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

Route::get('/support', function () {
    return view('pages.customer_support', [
        'marking' => null,
        'email' => null,
        'bookingReference' => null,
        'company' => null,
        'booking' => null
    ]);
})->name('support.fetch'); //duplicate name

Route::post('/support', function (Request $request) {

    $marking = $request->input('marking');
    $email = $request->input('customer_email');
    $bookingReference = $request->input('booking_reference');
    $billNo = $request->input('bill_no');
    $autocountDocNoInvoice = $request->input('autocount_docno_invoice');

    $company = null;
    $booking = null;

    if($email) {
        $company = Company::whereHas('Employees', function($user) use($email) {
            return $user->where('email', $email);
        })->first();
    }

    if($marking) {
        $company = Company::where('reference', $marking)->first();
    }

    if($bookingReference) {
        $booking = Booking::where('marking', $bookingReference)->first();
        $company = $booking->company;
    }

    if($billNo) {
        $transaction = Transaction::where('bill_no', $billNo)->first();
        if($transaction){
            $booking = $transaction->booking;
        }
    }

    if($autocountDocNoInvoice) {
        $kvp = KeyValuePair::where('key', KVPKey::AUTOCOUNT_DOCNO_INVOICE)->where('value', $autocountDocNoInvoice)->first();
        if($kvp){
            $transaction = $kvp->owner()->withTrashed()->first();
            $booking =  $transaction ? $transaction->booking : null;
        }
    }

    return view('pages.customer_support', [
        'marking' => $marking,
        'email' => $email,
        'bookingReference' => $bookingReference,
        'company' => $company,
        'booking' => $booking,
    ]);

})->name('support'); //duplicate name

Route::get('/online_payment/redirect', [CallbackBillplzController::class, 'callback'])->name('online_payment.redirect');

Route::get('/products', function (\App\Classes\Modules\Exports\Services\ExportsProducts $exportsProducts) {
    $exportFileName = 'products.csv';
    $filesystemDriver = Storage::getDefaultDriver();
    if($filesystemDriver === 's3'){
        return response([ 'src' =>  App\Classes\General\AWSS3Helper::S3Exportable($exportFileName, $exportsProducts) ]);
    }
    else{
        return $exportsProducts->download($exportFileName, Excel::CSV, ['Content-Type' => 'text/csv']);
    }
})->name('products.random.1'); //duplicate name

Route::get('/fix_bills', function () {
    ini_set('max_execution_time', '1000000');
    Auth()->login(User::find(1));
    $bookings = \App\Models\Booking::where('status', 3)->whereHas('transactions', function ($query){
        return $query->where('type', 1)->whereHas('transactions', function($query){
           return $query->where('type', 3)->where('issuer', 2210);
        });
    })->get();
    foreach ($bookings as $booking){
        $booking->documents()->where('document_type', DocumentType::SUPPLIER_DELIVER_ORDER)->delete();
        $po = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first();
        $supplier_deliver_order_transaction = $booking->transactions()->where('type', TransactionType::SUPPLIER_DELIVER)->first();
        $supplier = Company::find($booking->transactions()->where('type', TransactionType::PAYMENT)->where('status', 3)->first()->transactions()->first());
        $supplier_order_pdf = LaravelMpdf::loadView('pages.pdfs.supplier_deliver_order', ['supplier_deliver_order_transaction' => $supplier_deliver_order_transaction, 'po_order_transaction' => $po, 'supplier' => $supplier]);
        $document_object = new DocumentObject(
            DocumentType::SUPPLIER_DELIVER_ORDER,
            [chunk_split('data:application/pdf;base64,'.base64_encode($supplier_order_pdf->output()))],
            '',
            ApprovalStatus::COMPLETED,
            'supplier_delivery_orders'
        );

        $document = (App()->make(CreatesDocument::class))->execute($booking, $document_object);
        (App()->make(CreatesFiles::class))->execute($document, $document_object);
    }


})->name('products.random.2'); //duplicate name

Route::get('/wallet/{marking}/details', function ($marking) {
    $company = \App\Models\Company::where('reference', '=', $marking)->first();
    $id = $company->id;
    $wallet_id = $company->wallets()->first()->id;
    return view('pages.wallet.index', ['id' => $id, 'wallet_id' => $wallet_id]);
})->name('wallet.details');

Route::get('/wallet/{marking}/{is_precise}/export', [ExportCustomersWalletTransactionToExcelController::class, 'export'])->name('wallet.details-export');

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

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

Route::get('/document/download', [DownloadBookingDocumentController::class, 'download'])->name('documents.download');

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


Route::get('/export/customers/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'export'])->name('customers.export');
Route::get('/export/transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'transactions'])->name('transactions.export');
Route::get('/export/transactions/v2/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'v2transactions'])->name('transactions.v2.export');
Route::get('/export/null-debtor/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'nullDebtor'])->name('newDebtor.export');
Route::get('/export/payment-transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'paymentTransactions'])->name('paymentTransactions.export');
Route::get('/export/white-form-transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'whiteFormTransactions'])->name('whiteFormTransactions.export');
Route::get('/export/wallet-transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'walletTransactions'])->name('walletTransactions.export');
Route::get('/export/booking-transactions', [ExportCustomersToExcelController::class, 'bookingTransactions'])->name('export.transactions.booking');
Route::get('/export/invoice-transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'invoiceTransactions'])->name('invoiceTransactions.export');
Route::get('/export/receipt-transactions/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'receiptTransactions'])->name('receiptTransactions.export');
Route::get('/export/imported-invoice-mapped', [ExportCustomersToExcelController::class, 'importedInvoiceMapped'])->name('importedInvoiceMapped.export');
Route::get('/export/imported-receipt-mapped', [ExportCustomersToExcelController::class, 'importedReceiptMapped'])->name('importedReceiptMapped.export');
Route::get('/export/analytic/booking', [ExportAnalyticToExcelController::class, 'bookingData'])->name('bookingData.export');;
Route::get('/export/analytic/bills', [ExportAnalyticToExcelController::class, 'billingData'])->name('billingData.export');;
Route::get('/export/customers/leads', [ExportCustomersToExcelController::class, 'leadsData'])->name('leads.export');
Route::get('/export/excel/{id}', [ExportCustomersToExcelController::class, 'exportCurrencyVendorOrder'])->name('group.excel');
Route::get('/export/einv-debtor/f614e339d7058904a831aad742e24d55', [ExportCustomersToExcelController::class, 'eInvoiceDebtorSummary'])->name('eInvoiceDebtorSummary.export');
Route::get('/export/all-customers-info-for-lark-system', [ExportCustomersToExcelController::class, 'exportAllCustomersInfoForLarkSystem'])->name('exportAllCustomersInfoForLarkSystem.export');

Route::get('/products', function (\App\Classes\Modules\Exports\Services\ExportsProducts $exportsProducts) {
    $bookings = Booking::where(function($query){
        return $query->whereMonth('created_at', 7)->orWhereMonth('created_at', 8)->orWhereMonth('created_at', 9)->orWhereMonth('created_at', 10)->orWhereMonth('created_at', 11)->orWhereMonth('created_at', 12);
    })->whereDoesntHave('transactions', function($q){
        $q->where('type', TransactionType::PURCHASE_ORDER);
        $q->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED]);
    })->get();
    dd($bookings->count());

    $exportFileName = 'products.csv';
    $filesystemDriver = Storage::getDefaultDriver();
    if($filesystemDriver === 's3'){
        return response([ 'src' =>  App\Classes\General\AWSS3Helper::S3Exportable($exportFileName, $exportsProducts) ]);
    }
    else{
        return $exportsProducts->download('products.csv', Excel::CSV, ['Content-Type' => 'text/csv']);
    }
})->name('products.random.3');

Route::get('/auto-purchase-order-fill', [AutoPurchaseOrderFillController::class, 'auto'])->name('assign');

Route::get('purchase/sensitive/', function(Request $request){
    $keywords = json_decode($request->input('keywords'));
    $items = \App\Models\TransactionDetail::query();
    foreach ($keywords as $key => $keyword){
        if(!$key){
            $items->Where('product_name', 'like', '%'.$keyword.'%');
            continue;
        }

        $items->orWhere('product_name', 'like', '%'.$keyword.'%');
    }

    $items = $items->get();

    foreach ($items as $key => $item){
        echo ($key+1).'. '.$item->product_name.' => <a href="'.\route('booking.details', $item->transaction->owner->marking).'" target="_blank">'.$item->transaction->owner->marking.'</a><br><br>';
    }
});

Route::get('/transactions/supplier/{id}/mock_up', [DownloadMockUpWhiteFormPdfController::class, 'download'])->name('whiteForm.mockUp');

Route::get('/notifications/list', [ListNotificationsController::class, 'list'])->name('notifications.list');

Route::get('/supplier/pi/export/{month}/{year}/{id?}', function($month, $year, $id = null){

    if(!$id){
        foreach (Company::where('business_type', \App\Classes\ValueObjects\Constants\BusinessType::CURRENCY_VENDOR)->get() as $supplier) {
            echo '<a href="/supplier/pi/export/'.$month.'/'.$year.'/'.$supplier->id.'"><p>'.$supplier->name.'</p></a>';
        }

        return;
    }
    echo '<a href="/supplier/pi/export/'.$month.'/'.$year.'"><p>Back to suppliers list</p></a>';

    $groups = \App\Models\Group::where('issuer', $id)->whereMonth('created_at', $month)->whereYear('created_at', $year)->get();

   echo '<table>';
   $i = 0;
   foreach ($groups as $group){
        foreach ($group->transactions as $transaction){
            $booking = $purchaseOrder = $transaction->owner->owner;
            $purchaseOrder = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->where('status', ApprovalStatus::APPROVED)->first();
            if(!$purchaseOrder) {
                echo '<tr>';
                echo '<td>-</td>';
                echo '<td>'.$group->created_at.'</td>';
                echo '<td style="color: red">warning, booking ref.'.$booking->marking.' doesn\'t have purchase order</td>';
                echo '<td>0</td>';
                echo '<td>0</td>';
                echo '<td>0</td>';
                echo '<td>'.$booking->marking.'</td>';
                echo '</tr>';
                continue;
            }
            foreach ($purchaseOrder->transactionDetails as $item){
                $i++;
                echo '<tr>';
                echo '<td>'.$i.'</td>';
                echo '<td>'.$group->created_at.'</td>';
                echo '<td>'.$item->product_name.'</td>';
                echo '<td>'.$item->quantity.'</td>';
                echo '<td>'.$item->price * (1/$group->currency_rate).'</td>';
                echo '<td>'.($item->price * $item->quantity) * (1/$group->currency_rate).'</td>';
                echo '<td>'.$booking->marking.'</td>';
                echo '</tr>';

            }
        }

   }
    echo '<tr><td>Service Charge</td><td>'.$groups->sum('service_charge').'</td></tr>';
   echo '</table>';
});


Route::get('/segments', function (Request $request) {
    $segment = null;

    if ($request->has('id')) {
        $segment = App\Models\Segment::find($request->id);
    }

    return view('pages.segments.index', compact('segment'));
})->name('segments');

Route::get('/pending_orders', function(){
    $payments = Transaction::where('type', TransactionType::PAYMENT)->where('owner_type', Booking::class)->whereIn('status', [ApprovalStatus::APPROVED])
        ->whereDoesntHave('transactions', function ($query) {
            return $query->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::PENDING_SUBMISSION, ApprovalStatus::PENDING_VERIFICATION]);
        })
        ->whereDoesntHave('transactions', function ($transaction) {
            $transaction->whereHas('groupTransaction');
        })
        ->orderBy('updated_at', 'desc')
        ->get();

    echo '<table>';
    $i = 0;
    foreach ($payments as $payment){
        $booking = $payment->owner;
        $bank = $payment->bank ?? $booking->bank;

        $original_refunds = floatval((App()->make(CalculatesBookingRefundAmount::class))->calculateRefundAmount($payment, $booking->fix_currency_id));
        $refunds = $original_refunds / $payment->currency_rate;
        if(!$booking instanceof Booking){
            dd($payment);
        }
        $bankType = str::length($bank->holder_name) > 4 ? 'Company' : 'Personal';

        if (!preg_match('/[^A-Za-z0-9]/', $bank->holder_name))
        {
            $bankType = str_word_count($bank->holder_name) > 4 ? 'Company' : 'Personal';
        }

        echo '<tr>';
        echo '<td>'.$payment->updated_at->format('d-M-y').'</td>';
        echo '<td>'.$booking->marking.'</td>';
        echo '<td>'.\App\Classes\ValueObjects\Constants\PaymentMethodType::PAYMENT_METHODS_ID[$payment->payment_method].'</td>';
        echo '<td>'.$payment->currency->short_code.'</td>';
        echo '<td>'.number_format(bcsub($payment->amount, $refunds, 7), 5, '.', '').'</td>';
        echo '<td>'.$booking->company->reference.'</td>';
        echo '<td></td>';
        echo '<td>'.$payment->original_currency->short_code.'</td>';
        echo '<td>'.number_format(bcsub($payment->original_amount, $original_refunds, 7), 5, '.', '').'</td>';
        echo '<td></td>';
        echo '<td>'.$booking->service->name.'</td>';
        echo '<td>'.$payment->updated_at->diffForHumans().'</td>';
        echo '<td>'.$bankType.'</td>';
        echo '<td>'.$booking->bank->holder_name.'</td>';
        echo '</tr>';
    }
    echo '</table>';
})->name('orders.pending');

Route::get('/approve_refunds', function(Request $request){
    $type = $request->query('type');

    $approve_refunds = Transaction::where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);

    if (str_contains($type, 'partial')) {
        $approve_refunds->whereHas('owner', function ($q) {
            $q->whereColumn('original_amount', '!=', 'transactions.original_amount');
        });
    } else {
        $approve_refunds->whereHas('owner', function ($q) {
            $q->whereColumn('original_amount', 'transactions.original_amount');
        });
    }

    if (str_contains($type, 'post')) {
        $approve_refunds->whereHas('owner', function ($q) {
            $q->whereHas('transactions', function($query) {
                $query->where('type', TransactionType::SUPPLIER_REFUND);
            });
        });
    } else {
        $approve_refunds->whereHas('owner', function ($q) {
            $q->whereDoesntHave('transactions', function($query) {
                $query->where('type', TransactionType::SUPPLIER_REFUND);
            });
        });
    }


    // $payments = Transaction::where('type', TransactionType::PAYMENT)->where('owner_type', Booking::class)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED, ApprovalStatus::REFUNDED])
    //     ->whereHas('transactions', function ($query) use ($type) {
    //         $query->where('type', TransactionType::REFUND)->where('status', ApprovalStatus::APPROVED);
    //         if (str_contains($type, 'partial')) {
    //             $query->whereColumn('original_amount', '!=','transactions.original_amount');
    //         } else {
    //             $query->whereColumn('original_amount', 'transactions.original_amount');
    //         }
    //     });

    // if (str_contains($type, 'post')) {
    //     $payments->whereHas('transactions', function($query) {
    //         $query->where('type', TransactionType::SUPPLIER_REFUND);
    //     });
    // } else {
    //     $payments->whereDoesntHave('transactions', function($query) {
    //         $query->where('type', TransactionType::SUPPLIER_REFUND);
    //     });
    // }

    echo '<table>';
    echo '<tr>';
    echo '<td>No.</td>';
    echo '<td>Created At</td>';
    echo '<td>Marking</td>';
    echo '<td>Payment Method</td>';
    echo '<td colspan="2">Refunded Amount</td>';
    echo '<td>Company Reference</td>';
    echo '<td></td>';
    echo '<td colspan="2">Refunded Original Amount</td>';
    echo '<td></td>';
    echo '<td>Remark</td>';
    echo '<td>Service</td>';
    echo '<td>Last Updated At</td>';
    echo '<td>Bank Type</td>';
    echo '<td>Bank Holder Name</td>';
    echo '<td>Note Remark</td>';
    echo '</tr>';
    foreach ($approve_refunds->orderBy('created_at', 'DESC')->get() as $index => $refund){
        $payment = $refund->owner;
        $booking = $refund->owner->owner;
        $bank = $payment->bank ?? $booking->bank;

        if(!$booking instanceof Booking){
            dd($refund);
        }
        $bankType = str::length($bank->holder_name) > 4 ? 'Company' : 'Personal';

        if (!preg_match('/[^A-Za-z0-9]/', $bank->holder_name))
        {
            $bankType = str_word_count($bank->holder_name) > 4 ? 'Company' : 'Personal';
        }

        $remark = $refund->original_amount === $refund->owner->original_amount ? 'Fully Refund' : 'Partial Refund';

        if (str_contains($type, 'post')) {
            $remark = 'Post ' . $remark;
        } else {
            $remark = 'Pre ' . $remark;
        }

        $noteRemark = implode(', ', $refund->remarks->pluck('content')->toArray());

        echo '<tr>';
        echo '<td>'.($index + 1).'.</td>';
        echo '<td>'.$refund->created_at->format('d-M-y').'</td>';
        echo '<td>'.$booking->marking.'</td>';
        echo '<td>'.\App\Classes\ValueObjects\Constants\PaymentMethodType::PAYMENT_METHODS_ID[$payment->payment_method].'</td>';
        echo '<td>'.$payment->currency->short_code.'</td>';
        echo '<td>'.number_format($refund->amount, 5, '.', '').'</td>';
        echo '<td>'.$booking->company->reference.'</td>';
        echo '<td></td>';
        echo '<td>'.$payment->original_currency->short_code.'</td>';
        echo '<td>'.number_format($refund->original_amount, 5, '.', '').'</td>';
        echo '<td></td>';
        echo '<td>'.$remark.'</td>';
        echo '<td>'.$booking->service->name.'</td>';
        echo '<td>'.$payment->updated_at->diffForHumans().'</td>';
        echo '<td>'.$bankType.'</td>';
        echo '<td>'.$bank->holder_name.'</td>';
        echo '<td>'.$noteRemark.'</td>';
        echo '</tr>';
    }
    echo '</table>';
})->name('orders.refunds');

Route::get('/group/text/{id}', function($id){
    $group = \App\Models\Group::where('id', $id)->first();

    echo 'RATE: '.$group->currency_rate.'<br>';
    echo 'DATE: '.$group->created_at.'<br><br><br>';

    $i = 0;

    foreach ($group->transactions as $transaction){
        $i++;
        $booking = $transaction->owner->owner;
        $bank = $transaction->owner->bank ?? $booking->bank;

        echo 'No.'.$i.'<br>';
        echo 'Bank Details:'.$bank->holder_name.'<br>';
        echo $bank->bank_name.' '.$bank->bank_branch.'<br>';
        echo 'Bank Account Number:'.$bank->account_no.'<br>';
        echo 'Order Amount:'.$transaction->original_currency->short_code.' '.(round($transaction->original_amount, 2) + 0).'<br><br>';

    }
})->name('group.text');

Route::get('/group/invoice/{id}', function ($id) {

    $group = Group::findOrFail($id);

    $supplier = $group->issuerCompany;

    $transferFeeTransactions = $group->transactions()
        ->with(['transactions' => function ($transaction) {
            return $transaction->where('type', TransactionType::TRANSFER_FEE);
        }])
        ->get()
        ->pluck('transactions')
        ->flatten();

    $html = view('pages.pdfs.supplier_deliver_order_group_invoice', [
        'group'=> $group,
        'transactions' => $group->transactions,
        'transferFeeTransactions' => $transferFeeTransactions,
        'supplier' => $supplier
        ])->render();

        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();

        $exportFileName = "invoice_pdf_{$supplier->name}.pdf";
        $filesystemDriver = Storage::getDefaultDriver();
        if($filesystemDriver === 's3'){
            $pdfContent = $dompdf->output();
            return response([ 'src' =>  AWSS3Helper::S3PDF($exportFileName, $pdfContent) ]);
        }
        else{
            return $dompdf->stream($exportFileName);
        }
})->name('group.invoice');

Route::get('/wallet/audit', function (Request $request) {
    $wallets = \App\Models\Wallet::all();


    $i = 0;
    foreach ($wallets as $wallet){
        $topups = 0;
        $credit = 0;
        $payments = 0;
        $debit = 0;

        foreach ($wallet->transactions as $transaction){
            if(!in_array((int) $transaction->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) continue;
            if((int) $transaction->type === TransactionType::TOP_UP) {
                $topups += (float) $transaction->amount;
//                $response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$transaction->payment_reference);
//
//                if($response->successful()){
//                    $data = $response->json();
//                    if($data['paid']){
//
//                    } else {
//                        echo $transaction->id." => Fraud";
//                    }
//                }else{
//                   echo "billplz error";
//                }

            }
            if((int) $transaction->type === TransactionType::CREDIT_NOTE) $credit += (float) $transaction->amount;
            if((int) $transaction->type === TransactionType::PAYMENT) $payments += (float) $transaction->amount;
            if((int) $transaction->type === TransactionType::DEBIT_NOTE) $debit += (float) $transaction->amount;
        }
        $auditBalance = ($topups + $credit) - ($payments + $debit);
        $diffenrence = round((float) $wallet->amount - (($topups + $credit) - ($payments + $debit)), 2);
        if((($diffenrence == 0) || ($diffenrence == -0)) AND $wallet->amount > -0.01) continue;

        $i++;

        echo $i.". Marking: ". $wallet->owner->reference ."(".$wallet->id.")<br>Current Balance: ". $wallet->amount ."<br>Audit Balance: ". ($auditBalance) ."<br>Difference: ". $diffenrence ."<br><br><br>";
    }
});


Route::get('/wallets/active', function(){
    $wallets = Wallet::all();

    echo '<table>';
    foreach ($wallets as $wallet){
        echo '<tr>';
        echo '<td><a href="'.route('wallet.details', $wallet->owner->reference).'" target="_blank">'.$wallet->owner->reference.'</a></td>';
        echo '<td>'.$wallet->amount.'</td>';
        echo '</tr>';
    }
    echo '</table>';
});

Route::get('/payments/manual', function(){

    $payments = Transaction::where('type', TransactionType::PAYMENT)->whereIn('payment_method', [\App\Classes\ValueObjects\Constants\PaymentMethodType::CASH, \App\Classes\ValueObjects\Constants\PaymentMethodType::BA, \App\Classes\ValueObjects\Constants\PaymentMethodType::CHEQUE])->where('owner_type', Booking::class)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->get();

    $i = 0;
    echo '<table>';
    foreach ($payments as $payment){
        $i++;
        echo '<tr>';
        echo '<td>'.$i.'</td>';
        echo '<td>'.$payment->documents()->first()->created_at->format('d-m-Y').'</td>';
        echo '<td><a href="'.route('booking.details', $payment->owner->marking).'" target="_blank">'.$payment->owner->marking.'</a></td>';
        echo '<td>'.$payment->amount.'</td>';
        echo '</tr>';
    }
    echo '</table>';
});

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

    dd('Deprecated, call Tech Support');

    set_time_limit(14400);
    $processed_invoice = 1;

    Booking::where('status', ApprovalStatus::COMPLETED)
        ->whereDate('updated_at', '>=', Carbon::parse('01-01-2023'))
        ->orderBy('id')
        ->chunk(100, function ($bookings) use (&$processed_invoice) {
            foreach ($bookings as $booking) {

                LogHelper::channel('regenerateInvoice')->info('Counter ' . $processed_invoice);
                dump('Counter ' . $processed_invoice);
                $processed_invoice += 1;

                if ($booking->transactions()->where('transactions.type', TransactionType::INVOICE)
                    ->first()
                    ->created_at
                    ->greaterThanOrEqualTo(Carbon::parse('2023-09-07'))) {
                    continue;
                }

                $booking->transactions()->whereIn('transactions.type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->delete();
                $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete();
                $booking->status = ApprovalStatus::APPROVED;
                $booking->save();

                $deletedInvoice = $booking->transactions()
                    ->whereIn('type', [TransactionType::INVOICE])
                    ->onlyTrashed()
                    ->orderBy('created_at', 'asc')
                    ->first();

                if ($deletedInvoice) {
                    $bill_no = $deletedInvoice->bill_no;

                    // check if bill_no ends with '-deleted'
                    if (str_ends_with($bill_no, '-deleted')) {
                        $bill_no = str_replace('-deleted', '', $bill_no);
                    }

                    $deletedInvoice->bill_no = $bill_no . '-deleted';
                    $deletedInvoice->save();

                    $existing_invoice_bill_no = Transaction::withTrashed()->where('bill_no', $bill_no)->first();

                    if ($existing_invoice_bill_no) {
                        LogHelper::channel('regenerateInvoice')->info('Delete existing bill_no');
                        LogHelper::channel('regenerateInvoice')->info(json_encode($existing_invoice_bill_no));
                        $existing_invoice_bill_no->forceDelete();
                    }

                    (App()->make(CreateInvoiceTransactionV2Processor::class))->execute($booking, $bill_no);
                    dump('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no);
                    LogHelper::channel('regenerateInvoice')->info('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $bill_no . '. Old bill_no - ' . $deletedInvoice->bill_no);
                } else {
                    (App()->make(CreateInvoiceTransactionV2Processor::class))->execute($booking);
                    dump('regenerated new invoice. Booking Marking - ' . $booking->marking);
                    LogHelper::channel('regenerateInvoice')->info('regenerated new invoice. Booking Marking - ' . $booking->marking);
                }
            }
        }
    );
})->name('invoice.fix');

Route::get('/1688/fix/{reference}', function($reference){

    $booking = Booking::where('marking', $reference)->first();

    (App()->make(createPurchaseOrderFor1688OrderProcessor::class))->execute($booking);

//    set_time_limit(1800);
//    $purchaseOrderDocuments = \App\Models\Document::where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER)->get();
//
//    foreach($purchaseOrderDocuments as $document){
//        $booking = $document->owner;
//        $booking->status = ApprovalStatus::APPROVED;
//        $booking->save();
//
//        $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete();
//
//        (App()->make(createPurchaseOrderFor1688OrderProcessor::class))->execute($document->owner);
//    }
})->name('ecommerce.fix'); //duplicate name

// Route::get('/po/manual/fix', function(){

// //    $bookings = Booking::whereIn('company_id', [199, 510])->whereHas('documents', function($query){
// //        return $query->where('document_type', DocumentType::ECOMMERCE_PURCHASE_ORDER);
// //    })->get();
// //
// //    foreach ($bookings as $booking){
// //        $booking->status = ApprovalStatus::APPROVED;
// //        $booking->save();
// //
// //        $booking->documents()->whereIn('document_type', [DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::INVOICE, DocumentType::SUPPLIER_DELIVER_ORDER])->delete();
// //        $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->update(['status' => ApprovalStatus::PENDING_SUBMISSION]);
// //
// //    }

// })->name('ecommerce.fix'); //duplicate name

Route::get('/payment/check', function(){

    $transactions = Transaction::where('type', TransactionType::BILL)->whereDate('created_at', '>=', Carbon::today())->get();

    foreach ($transactions as $transaction){
        $booking = $transaction->owner->owner;
        $documents = $transaction->documents;
        if(!count($documents)){
            echo $booking->marking.'<br><br>';
            continue;
        }

//        echo $transaction->owner->owner->marking.'. payment: '.$transaction->updated_at.' -> document: '.$documents[0]->created_at.'<br>';
    }


})->name('payment.check');

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

    $bookings = Booking::whereIn('marking', [82935, 92135, 96183, 94448, 29819, 30403, 63969, 42116, 79278, 89987, 51432, 76289, 67767, 98433, 47431, 93472, 50933, 87298, 35329, 93845, 55902, 82629, 51019, 42820, 90666, 40167, 29253, 48891, 67364, 64628, 91859, 22123, 34154, 84366, 27370, 58222, 67695, 71233, 26466, 83894, 35664, 65669, 68986, 40382, 63743, 39611, 60658, 32893, 98243, 23822, 64323, 79271, 79053, 48497, 48708, 86463, 30054, 50590, 85808, 88988, 79663, 57558, 85902, 95451, 95897, 33164, 82342, 38091, 27451, 64809, 39444, 32101, 27242, 71851, 50850, 70659, 89403, 55540, 65743, 77315, 22921, 35623, 77315, 32344, 81717, 57176, 48775, 34133, 39396, 67473, 42749, 89395, 32132, 23670, 36783, 21783, 66348, 47205, 72784, 22437, 96271, 45396, 45352, 47896, 61654, 73174, 47002, 25448, 95810, 80827, 81180, 52142, 37640, 30295, 59816, 99197, 76541, 94786, 30776, 89769, 77720, 30610, 28546, 50931, 94525, 43425, 37461, 20629, 60586, 87228, 24814, 68011, 90547, 30572, 26274, 26274, 38599, 44487, 96767, 63872, 29576, 20173, 23555, 64657, 71021, 65316, 86540, 73981, 32747, 71086, 83221, 66168, 90541, 52366, 29227, 30915, 45242, 81384, 37533, 89752, 70133, 45894, 21918, 85579, 48650, 88747, 23200, 37018, 21753, 21188, 60449, 63918, 68888, 49910, 30402, 96338, 36578, 82133, 37872, 90437, 54404, 73439, 94283, 97752, 83333, 38548, 74366, 21060, 43240, 94612, 33164, 98630, 33164, 22898, 44320, 31153, 36480, 55085, 64039, 99796, 42238, 71458, 34415, 49935, 37902, 25598, 51833, 89733, 38081, 71564, 51366, 20173, 91400, 86540, 92131, 76724, 22657, 62117, 86443, 85827, 46570, 99809, 89258, 68834, 20785, 24478, 79588, 49111, 24838, 41989, 79081, 48440, 57375, 86104, 78719, 61502, 96167, 23398, 27873, 80065, 33048, 83138, 99211, 98183, 28639, 54547, 70098, 27216, 67404, 47761, 85049, 41906, 62328, 63645, 46750, 86975, 69955, 21714, 33889, 87344, 58345, 34183, 82504, 68636, 70962, 92553, 20125, 88625, 20661, 98146, 92075, 67543, 99045, 27395, 67163, 32245, 43347, 87947, 97897, 59860, 26003, 47852, 96008, 54166, 50037, 31435, 35821, 81929, 76751, 80379, 32473, 81598, 58716, 70554, 67473, 82491, 93859, 99159, 84772, 84772, 32473, 42050, 26532, 81526, 81526, 45780, 46570, 78657, 35293, 98311, 62095, 86914, 45215, 37650, 57708, 60449, 46750, 91834, 60989, 54877, 98298, 52382, 86346, 65219])
    ->get();

    $notPlaced = [];
    $placed = [];
    $completed = [];

    foreach ($bookings as $booking){
        $payments = $booking->transactions()->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->get();
        foreach ($payments as $payment){
            if($payment->status === ApprovalStatus::APPROVED){
                $notPlaced[] = $booking;
                continue;
            }

            $bill = $payment->transactions()->where('type', TransactionType::BILL)->first();
            if(!$bill){
                $notPlaced[] = $booking;
                continue;
            }

            if(in_array($bill->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])){
                $completed[] = $booking;
                continue;
            }
            $placed[] = $booking;
        }
    }

    echo '<h3>Customer Paid ('.count($notPlaced).')</h3>';
    foreach ($notPlaced as $booking){
        echo '<a href="'.route('booking.details', $booking->marking).'" target="_blank">'.$booking->marking.'</a><br>';
    }

    echo '<h3>White Form Generated ('.count($placed).')</h3>';
    foreach ($placed as $booking){
        echo '<a href="'.route('booking.details', $booking->marking).'" target="_blank">'.$booking->marking.'</a><br>';
    }

    echo '<h3>China Bankslip Uploaded ('.count($completed).')</h3>';
    foreach ($completed as $booking){
        echo '<a href="'.route('booking.details', $booking->marking).'" target="_blank">'.$booking->marking.'</a><br>';
    }

});

Route::get('/currency-rate-history', function () {
    $paymentMethods = PaymentMethodType::PAYMENT_METHODS;
    return view('pages.rate_histories')->with('paymentMethods', $paymentMethods);
})->name('currency_rate.history');

Route::get('/statements', [BankStatementController::class, 'index'])->name('statements.index');
Route::get('/statements/v2', [BankStatementController::class, 'indexv2'])->name('statements.indexv2');
Route::post('/statements/import', [BankStatementController::class, 'import'])->name('statements.import');
Route::get('/statements/{statement}/details', function ($statement) {
    return view('pages.accounting.bank-statements.details', ['statement' => $statement]);
})->name('statements.transactions.details');
Route::get('/statements/{account}/transactions', function ($account) {
    return view('pages.accounting.bank-statements.bank_statement', ['account' => $account]);
})->name('statements.account.transactions');
Route::get('/statements/{statement}', [BankStatementController::class, 'show'])->name('statements.show');
Route::get('/statements/mapping/rerun', [BankStatementController::class, 'rerun'])->name('statements.rerun');
// Route::get('/statements/{statement}/download', 'StatementController@download')->name('statements.download');
Route::get('/bank-record', [ImportBankRecordController::class, 'import']);

Route::get('/po/outsource/check', function(){
    $bookings = Booking::whereIn('marking', [34735, 43980, 35339, 28104, 40185, 46648, 34192, 21512, 84607, 31319, 23566, 48372, 59239, 72665, 81127, 46881, 41055, 67368, 41817, 60443, 28958, 46782, 98512, 43356, 78469, 88173, 52592, 77036, 76750, 77732, 31980, 57146, 38544, 78567, 98297, 90128, 43680, 86478, 80340, 41961, 26857, 33992, 79929, 53226, 88107, 31187, 68015, 43762, 34928, 55525, 44528, 57146, 31980, 27399, 63141, 74987, 85935, 37032, 95911, 59511, 47395, 97293, 43906, 74944, 53418, 61988, 81406, 83889, 83359, 66896, 21425, 61124, 23536, 56129, 21116, 64213, 72950, 20502, 20067, 64213, 59854, 44783, 35681, 74828, 28179, 32961, 46412, 99908, 49008, 77655, 45250, 65047, 37167, 90598, 26275, 58013, 38994, 63187, 33219, 52669, 79885, 74828, 91775, 29282, 46781, 96415, 36318, 84491, 32659, 23846, 38994, 65329, 25936, 68209, 72866, 63231, 32216, 82977, 24819, 32600, 38019, 80872, 65505, 37236, 82262, 30815, 59033, 46776, 87317, 89548, 36548, 54468, 35340, 98242, 29234, 47129, 67047, 64210, 36698, 39353, 86435, 65240, 37116, 71007, 40148, 88187, 76368, 91155, 57040, 95456, 29961, 66447, 43023, 29396, 30637, 60789, 84221, 35805, 44552, 35524, 43457, 22810, 83545, 92252, 83603, 59797, 40526, 32520, 71011, 95151, 90464, 78629, 61225, 74864, 73518, 53793, 26478, 57640, 43674, 23476, 76683, 23920, 22810, 44603, 56291, 23580, 94241, 51565, 83769, 63123, 58369, 99399, 41098, 60942, 69442, 80963, 48392, 73169, 59764, 66099, 21107, 33029, 38288, 32223, 55931, 43685, 24267, 83865, 52066, 61501, 83210, 20731, 55951, 82502, 66618, 62216, 22020, 42402, 99644, 35305, 49263, 37387, 73928, 92279, 26445, 83497, 96740, 38374, 29273, 94073, 99785, 21502, 51269, 31609, 97369, 73078, 28982, 64902, 41380, 87008, 59377, 39441, 81341, 62750, 29410, 85975, 37215, 43386, 80627, 79967, 81729, 81738, 58658, 40579, 56179, 37548, 72436, 77165, 32069, 97447, 84575, 49167, 45507, 96371, 90835, 27942, 87691, 30431, 47815, 82960, 43228, 87534, 93737, 98938, 69548, 82923, 48463, 24385, 96569, 53812, 32926, 54418, 34399, 53189, 49377, 27036, 68832, 72799, 76120, 78203, 87009, 86992, 97722, 96262, 95551, 77632, 54408, 33931, 62397, 58343, 52347, 59419, 50339, 54941, 31199, 92385, 90028, 90379, 43070, 25357, 24591, 60276, 91851, 96371, 81886, 24377, 21236, 66737, 93637, 85844, 23130, 75659, 27318, 43587, 46555, 28903, 44930, 52377, 20387, 40705, 79255, 29196, 30968, 76319, 54600, 29881, 37920, 43319, 35893, 65863, 33102, 71589, 45905, 49031, 97435, 70157, 78795, 47570, 71881, 92076, 45847, 35957, 58785, 84896, 65918, 25550, 49031, 50624, 83286, 63111, 21402, 56300, 77238, 21271, 21984, 30500, 76170, 95325, 22888, 84895, 26100, 84952, 49302, 41944, 43703, 84028, 53672, 49162, 28342, 47182, 70484, 59467, 85415, 20202, 97967, 58011, 85807, 79868, 81192, 86985, 43867, 47473, 28063, 68849, 61628, 96641, 37285, 58384, 86505, 51720, 63951, 91958, 28082, 46229, 57439, 55178, 96813, 34444, 28100, 75967, 33204, 75922, 68707, 71960, 34769, 29161, 49088, 79773, 91131, 53033, 77611, 81034, 72625, 36273, 78240, 34647, 21838, 73195, 83282, 60911, 29019, 98859, 44064, 82113, 51118, 54681, 59751, 64347, 21623, 47023, 62168, 23466, 62137, 85432, 85043, 41984, 30417, 40616, 97170, 69106, 81484, 68902, 78149, 62438, 67710, 57370, 99207, 64271, 33959, 60821, 51292, 44130, 28469, 77069, 91088, 47702, 89046, 84958, 41601, 99752, 72976, 26393, 85548, 32920, 86353, 97430, 71507, 36667, 57059, 71148, 44588, 35807, 80213, 89884, 76616, 35999, 79860, 37284, 72249, 32885, 70622, 47036, 97366, 60483, 89171, 37048, 34227, 76290, 46761, 31389, 73977, 54421, 87527, 75925, 68236, 31131, 43871, 54753, 90896, 41653, 82304, 87123, 80391, 42368, 35553, 60587, 30941, 31843, 25076])
        ->get();

    $averageItems = 5;
    $totalItems = 0;
    $pay = 0;

    foreach ($bookings as $booking){
        $po = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::PENDING_VERIFICATION])->first();

        if(!$po){
            echo '<span style="color: red">'.$booking->marking.' Purchase order not found!</span><br>';
            continue;
        }

//        $items = $po->transactionDetails()->get();
//
//        foreach ($items as $item){
//            $activity = Activity::where('causer_id', 4332)->where('subject_id', $item->id)->where('subject_type', \App\Models\TransactionDetail::class)->get();
//            if($activity) {
//                $totalItems++;
//            }
//        }
//        // check activities by user
        $itemsCount = $po->transactionDetails()->count();
        $totalItems += $itemsCount;

        $sum = $itemsCount / $averageItems;

        $pay += $sum < 1 ? 1 : round($sum);

    }

    echo '<h3>Total Items: '.$totalItems.'</h3>';
    echo '<h3>Total Pay: '.$pay.'</h3>';

});

Route::get('/upload-honey-trap', function () {
    return view('pages.honey_trap');
})->name('upload_honey_trap');

Route::get('/open-purchase-order/{marking}/{from_date}/{to_date}', function ($marking, $from_date, $to_date, DeletesTransaction $deletesTransaction, DeletesDocument $deletesDocument) {
    $company_id = Company::where('reference', $marking)->first()->id;

    $startDate = Carbon::createFromFormat('d-m-Y', $from_date)->startOfDay();
    $endDate = Carbon::createFromFormat('d-m-Y', $to_date)->endOfDay();

    $bookings = Booking::where('company_id', $company_id)->whereBetween('created_at', [$startDate, $endDate])->get();

    foreach ($bookings as $booking) {
        $booking->status = ApprovalStatus::APPROVED;
        $booking->save();

        $transaction = $booking->transactions()->whereIn('type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->get();
        foreach ($transaction as $key => $row) {
            $deletesTransaction->execute($row);
        }

        $document = $booking->documents()->whereIn('document_type', [DocumentType::PURCHASE_ORDER, DocumentType::INVOICE, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->get();
        foreach ($document as $key => $row) {
            $deletesDocument->execute($row);
        }

        $puchase_order = $booking->transactions()->where('type', TransactionType::PURCHASE_ORDER)->first();
        if($puchase_order) {
            $puchase_order->status = ApprovalStatus::PENDING_SUBMISSION;
            $puchase_order->save();
        }

        dump('done - ' . $booking->marking);
    }
});

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

Route::get('/customer/vouchers/{marking}', function ($marking) {
    $company = \App\Models\Company::where('reference', '=', $marking)->first();
    if($company){
        $id = $company->employees->first()->id;
        return view('pages.customers.reward', ['id' => $id]);
    }
    else{
        abort(404);
    }
})->name('customer.reward');

Route::get('transaction/{id}/credit_note/download', [GenerateCreditNotePdfController::class, 'downloadV2'])->name('transaction.credit_note.download');
Route::get('transaction/{id}/credit_note/download/v2', [GenerateCreditNotePdfController::class, 'downloadV2'])->name('transaction.credit_note.download.v2');

Route::get('/invoice/{marking}/{started_at}/{ended_at}/fix', function($marking, $started_at, $ended_at) {

    dd('Deprecated, call Tech Support');

    set_time_limit(14400);
    $processed_invoice = 1;

    if (is_null($marking) || empty($marking)) {
        return 'Error - Marking is empty';
    }

    if (is_null($started_at) || empty($started_at)) {
        return 'Error - Start Date is empty';
    }

    if (is_null($ended_at) || empty($ended_at)) {
        return 'Error - End Date is empty';
    }

    $company = Company::where('reference', $marking)->first();
    if (!$company) {
        return 'Error - Marking not found';
    }
    dump('Company Id - ' . $company->id);

    // dd($marking, $started_at, $ended_at);

    $bookings = $company->bookings()
        ->where('status', ApprovalStatus::COMPLETED)
        ->whereDate('created_at', '>=', Carbon::parse($started_at))
        ->whereDate('created_at', '<=', Carbon::parse($ended_at))
        ->orderBy('id')
        ->chunk(100, function ($bookings) use (&$processed_invoice) {
            foreach ($bookings as $booking) {

                LogHelper::channel('regenerateInvoice')->info('Counter ' . $processed_invoice);
                dump('Counter ' . $processed_invoice);
                dump('Marking ' . $booking->marking);
                $processed_invoice += 1;

                $booking->status = ApprovalStatus::APPROVED;
                $booking->save();

                $firstInvoice = $booking->transactions()
                    ->whereIn('type', [TransactionType::INVOICE])
                    ->withTrashed()
                    ->orderBy('created_at', 'asc')
                    ->first();

                // get the first bill_no
                $firstBillNo = $firstInvoice->bill_no;
                if (strpos($firstBillNo, '-deleted') !== false) {
                    $firstBillNo = substr($firstBillNo, 0, strpos($firstBillNo, '-deleted'));
                }

                // update currentInvoice bill_no to '-deleted-'
                $currentInvoice = $booking->transactions()->where('type', TransactionType::INVOICE)->first();
                $currentInvoice->bill_no = $currentInvoice->bill_no ."-deleted-" . Str::random(10);
                $currentInvoice->save();

                $transactionWithSameBillNo = Transaction::where('bill_no', $firstBillNo)->withTrashed()->get();
                if ($transactionWithSameBillNo) {
                    foreach ($transactionWithSameBillNo as $transaction) {
                        $transaction->bill_no = $transaction->bill_no . "-deleted-" . Str::random(10);
                        $transaction->save();
                    }
                }

                $booking->transactions()->whereIn('transactions.type', [TransactionType::INVOICE, TransactionType::SUPPLIER_DELIVER])->delete();
                $booking->documents()->whereIn('document_type', [DocumentType::INVOICE, DocumentType::PURCHASE_ORDER, DocumentType::DELIVER_ORDER, DocumentType::SUPPLIER_DELIVER_ORDER])->delete();

                (App()->make(CreateInvoiceTransactionV2Processor::class))->execute($booking, $firstBillNo);
                dump('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $firstBillNo . '. Old bill_no - ' . $currentInvoice->bill_no);
                LogHelper::channel('regenerateInvoice')->info('regenerated invoice. Booking Marking - ' . $booking->marking . '. Bill_no - ' . $firstBillNo . '. Old bill_no - ' . $currentInvoice->bill_no);
            }
        }
    );
})->name('invoice.fix.byCustomerMarking');

Route::post('/transaction/{id}/create-remark',function ($transactionId) {
    $transaction = Transaction::find($transactionId);
    $remark = new Remark();

    $remark->owner_type = get_class($transaction);
    $remark->owner_id = $transaction->id;

    $remark->content = request('content');
    $remark->save();
    return redirect()->back();
})->name('transaction.create-remark');

Route::get('/show-white-form-transactions-in-date-range/{from_date}/{to_date}', function ($from_date, $to_date) {

    $approvedTransactions = Transaction::where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->where('owner_type', '!=', Wallet::class)->orderBy('status')->get();

    echo '<h1>Pending Orders Payments</h1>';
    echo '<table style="border-collapse: collapse;">';
    echo '<thead>';
    echo '<tr>';
    echo '<th style="border: 1px solid black;">Booking</th>';
    echo '<th style="border: 1px solid black;">Amount</th>';
    echo '<th style="border: 1px solid black;">Payment Date</th>';
    echo '<th style="border: 1px solid black;">Status</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';

    foreach ($approvedTransactions as $approvedTransaction) {
        echo '<tr>';
        echo '<td style="border: 1px solid black;"><a href="' . \route('booking.details', $approvedTransaction->owner->marking) . '" target="_blank">' . $approvedTransaction->owner->marking . '</a></td>';
        echo '<td style="border: 1px solid black;">' . round($approvedTransaction->amount, 2) . '</td>';
        echo '<td style="border: 1px solid black;">' . $approvedTransaction->created_at->format('d-m-Y h:i A') . '</td>';
        echo '<td style="border: 1px solid black;">' . ApprovalStatus::APPROVAL_STATUS_ID[$approvedTransaction->status] . '</td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';

    $startDate = Carbon::createFromFormat('d-m-Y', $from_date)->startOfDay();
    $endDate = Carbon::createFromFormat('d-m-Y', $to_date)->endOfDay();


    echo '<h1>Bills in the date range</h1>';
    echo '<table style="border-collapse: collapse; width: 100%;">';
    echo '<thead>';
    echo '<tr>';
    echo '<th style="border: 1px solid black;">Booking</th>';
    echo '<th style="border: 1px solid black;">Amount</th>';
    echo '<th style="border: 1px solid black;">Customer payment date</th>';
    echo '<th style="border: 1px solid black;">White form date</th>';
    echo '<th style="border: 1px solid black;">Supplier</th>';
    echo '<th style="border: 1px solid black;">Upload bank slip Date</th>';
    echo '<th style="border: 1px solid black;">PO submit date</th>';
    echo '<th style="border: 1px solid black;">PO approve date</th>';
    echo '<th style="border: 1px solid black;">Remark</th>';
    echo '<th style="border: 1px solid black;">Add Remarks</th>';
    echo '<th style="border: 1px solid black;">Upload Bank Slip</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';


    $bills = Transaction::where('type', TransactionType::BILL)->whereBetween('created_at', [$startDate, $endDate])->get();

    foreach ($bills as $bill) {
        echo '<tr>';
        $payment = $bill->owner;
        $po = $payment->owner->transactions()->where('type', TransactionType::PURCHASE_ORDER)->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->first();
        echo '<td style="border: 1px solid black;"><a href="' . \route('booking.details', $bill->owner->owner->marking) . '" target="_blank">' . $payment->owner->marking . '</a></td>';
        echo '<td style="border: 1px solid black;">' . round($payment->amount, 2) . '</td>';
        echo '<td style="border: 1px solid black;">' . $payment->created_at->format('d-m-Y h:i A') . '</td>';
        echo '<td style="border: 1px solid black;">' . $bill->created_at->format('d-m-Y h:i A') . '</td>';
        echo '<td style="border: 1px solid black;">' . $bill->issuerCompany->name . '</td>';
        echo '<td style="border: 1px solid black; color: '.($bill->status === ApprovalStatus::APPROVED ? "green" : "red").';">' . ($bill->status === ApprovalStatus::APPROVED ? $bill->updated_at->format('d-m-Y h:i A') : 'Pending Upload') . '</td>';
        echo '<td style="border: 1px solid black; color: '.($po ? "green" : "red").';">' . ($po ? $po->updated_at->format('d-m-Y h:i A') : '<a href="' . \route('booking.details', $bill->owner->owner->marking) . '" target="_blank">Pending Submission</a>') . '</td>';
        echo '<td style="border: 1px solid black;">' . ($po ? ($po->status === ApprovalStatus::APPROVED ? $po->updated_at->format('d-m-Y h:i A') : '' ) : '' ). '</td>';
        $remarks = $bill->remarks;
        echo '<td style="border: 1px solid black;">';
            foreach ($remarks as $remark) {
                echo $remark->created_at->format('d-m-Y : h:i A') . ' - ';
                echo $remark->content;
                echo '<br>';
            }
        echo '</td>';
        echo '<td style="border: 1px solid black;">' ;
        echo '<form method="post" style="display:flex; margin: 10px" action="' . route('transaction.create-remark', ['id' => $bill->id]) . '">';
        echo '<input type="text" name="content" placeholder="Enter remark" required>';
        echo '<button type="submit">Add</button>';
        echo csrf_field();
        echo '</form>';
        echo '</td>';
        echo '<td style="border: 1px solid black;">' ;
        if ($bill->status !== ApprovalStatus::APPROVED) {
            echo '<form id="uploadForm-'.$bill->id.'" enctype="multipart/form-data" style="display:flex; margin: 10px">';
            echo '<input type="file" name="files[]" multiple required>';
            echo '<button type="button" onclick="uploadFiles('.$bill->id.')">Upload</button>';
            echo csrf_field();
            echo '</form>';
        }
        echo '</td>';
        echo '</tr>';
    }

    echo '</tbody>';
    echo '</table>';
     // script
     echo '<script>
     function uploadFiles(billId) {
         const form = document.getElementById("uploadForm-" + billId);
         const fileInput = form.querySelector("input[type=\'file\']");
         const files = fileInput.files;
         const userToken = localStorage.getItem("user-token");

         if (files.length === 0) {
             alert("Please select at least one file to upload.");
             return;
         }

         const fileReaders = [];
         let totalFiles = files.length;

         // Create a promise for each file to read it as Base64
         Array.from(files).forEach((file) => {
             const reader = new FileReader();

             // Create a promise that resolves when the file is read
             const fileReadPromise = new Promise((resolve, reject) => {
                 reader.onload = (event) => {
                     resolve(event.target.result);
                 };

                 reader.onerror = (error) => {
                     reject(error);
                 };

                 reader.readAsDataURL(file); // Read the file as Data URL (Base64)
             });

             fileReaders.push(fileReadPromise);
         });

         // Wait for all files to be read
         Promise.all(fileReaders)
             .then((fileData) => {
                 const payload = {
                     files: fileData, // Array of objects with name, type, and Base64 content
                 };

                 // Send the payload as JSON
                 return fetch(`/api/v1/transactions/${billId}/bill/verification`, {
                     method: "POST",
                     headers: {
                         "Authorization": "Bearer " + userToken,
                         "Content-Type": "application/json" // Sending JSON payload
                     },
                     body: JSON.stringify(payload),
                 });
             })
             .then(response => {
             console.log(response);
                 if (response.ok) {
                     alert("Files uploaded successfully!");
                     location.reload();
                 } else {
                     alert("Upload failed");
                 }
             })
             .catch(error => {
                 console.error("Error:", error);
                 alert("An error occurred during the upload.");
             });
     }
     </script>';
});

Route::get('check-duplicate-refunds', function () {
    $results = Transaction::select('payment_reference', 'owner_id', 'owner_type', 'type', 'status', 'amount', DB::raw('COUNT(*) as count'))
    ->whereNotNull('payment_reference')
    ->where('payment_reference', '<>', '')
    ->where('payment_reference', '<>', 'Withdraw')
    ->where('payment_reference', '<>', 'Refund for Ref. 77315')
    ->whereNull('deleted_at')
    ->groupBy('payment_reference', 'owner_id', 'owner_type', 'type', 'status', 'amount')
    ->having(DB::raw('COUNT(*)'), '>', 1)
    ->get();

    $transactionType = TransactionType::ID_TO_NAME;
    $approvalStatus = ApprovalStatus::APPROVAL_STATUS_ID;

    echo '<table style="border-collapse: collapse; width: 100%;">';
    echo '<thead>';
    echo '<tr>';
    echo '<th style="border: 1px solid black;">Owner Type</th>';
    echo '<th style="border: 1px solid black;">Owner ID</th>';
    echo '<th style="border: 1px solid black;">Payment Reference</th>';
    echo '<th style="border: 1px solid black;">Type</th>';
    echo '<th style="border: 1px solid black;">Status</th>';
    echo '<th style="border: 1px solid black;">Count</th>';
    echo '<th style="border: 1px solid black;">Amount</th>';
    echo '<th style="border: 1px solid black;">Wallet Details</th>';
    echo '<th style="border: 1px solid black;">Booking Ref</th>';
    echo '<th style="border: 1px solid black;">Payment ID</th>';
    echo '<th style="border: 1px solid black;">Payment Status</th>';
    echo '<th style="border: 1px solid black;">Refund ID</th>';
    echo '</tr>';
    echo '</thead>';
    echo '<tbody>';

    foreach ($results as $result) {
        $booking_ref_arr = explode(' ', $result->payment_reference);
        $booking_ref = end($booking_ref_arr);

        echo '<tr>';
        echo "<td style='border: 1px solid black;'>$result->owner_type</td>";
        echo "<td style='border: 1px solid black;'>$result->owner_id</td>";
        echo "<td style='border: 1px solid black;'>$result->payment_reference</td>";
        $status = $transactionType[$result->type];
        echo "<td style='border: 1px solid black;'>$status</td>";
        $approvalsName = $approvalStatus[$result->status];
        echo "<td style='border: 1px solid black;'>$approvalsName</td>";
        echo "<td style='border: 1px solid black;'>$result->count</td>";
        echo "<td style='border: 1px solid black;'>$result->amount</td>";

        $click = null;
        if ($result->owner_type == 'App\Models\Wallet') {
            $click = '<a href="'.route('wallet.details', $result->owner->owner->reference).'" target="_blank">'.$result->owner->owner->reference.'</a>';
        }
        echo "<td style='border: 1px solid black;'>". $click ."</td>";

        $booking_ref_click = null;
        $payment = null;
        $refund = null;
        if ($booking_ref) {
            $booking_ref_click = '<a href="'.route('booking.details', $booking_ref).'" target="_blank">'.$booking_ref.'</a>';

            $booking = Booking::where('marking', $booking_ref)->first();
            if ($booking) {
                $payment = $booking->transactions()->where('type', TransactionType::PAYMENT)->first();
                $refund = $payment->transactions()->where('type', TransactionType::REFUND)->get()->pluck('id')->toArray();
                $refund = implode(',', $refund);
            }
        }
        echo "<td style='border: 1px solid black;'>$booking_ref_click</td>";
        echo "<td style='border: 1px solid black;'>" . ($payment ? $payment->id : '') . "</td>";
        echo "<td style='border: 1px solid black;'>" . ($payment ? $approvalStatus[$payment->status] : '') . "</td>";
        echo "<td style='border: 1px solid black;'>" . ($refund ? $refund : '') . "</td>";
        echo '</tr>';


    }
    echo '</tbody>';
    echo '</table>';
});

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

Route::get('/site.webmanifest', function () {
    $filePath = resource_path('assets/images/favicon/site.webmanifest');

    if (!File::exists($filePath)) {
        abort(404);
    }

    $contents = File::get($filePath);
    return response($contents, 200)->header('Content-Type', 'application/manifest+json');
});


Route::get('/test-test', function () {
    dd('test-test');
});

Route::get('/maintenance', function () {
    return response()->view('errors.503', [], 503);
});

// web route to view the result
Route::get('/preview-unfinished-payment-orders', function (Request $request) {
    return (new UnfinishedPaymentOrders())->loadView($request);
});
// web route to run the logic
Route::get('/run-batch-unfinished-payment-orders', function (Request $request) {
    return (new UnfinishedPaymentOrders())->execute($request);
});


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

// Landing Pages
$landingPages = [
    '1688-payment-alternative-cn',
    'en-1688-vip-landing-page-general-fb',
    'en-1688-vip-landing-page-general-google',
    '1688-vip-payment-landing-page-wf-comparison-fb',
    '1688-vip-payment-landing-page-general-fb',
    '1688-vip-payment-landing-page-wf-comparison-google',
    '1688-vip-payment-landing-page-general-google',
];
foreach ($landingPages as $landingPage) {
    Route::get('/'.$landingPage, function () use ($landingPage) {
        return view('pages.landing.'.$landingPage);
    })->name('landing.'.$landingPage);
}
