<?php

use App\Booking;
use App\Http\Controllers\InvoiceController;
use App\Invoice;
use App\InvoiceStatuses;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
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('/', 'WelcomeController@index');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.request');
Route::post('password/reset', 'Auth\ResetPasswordController@postReset')->name('password.reset');
Route::get('/products', function(){
    DB::table('invoice_details')->update([
        'description' => 'Confidential Product Description',
        'stock_code' => '########',
        'quantity' => '1',
        'unit_price_rmb' => '1',
        'unit_price_rm' => '1',
        'total' => '1',
    ]);
});
Route::get('/bookings', function(){
    DB::beginTransaction();
    $lastRate = 1;
    $faker = Faker\Factory::create();
    $bookings = Booking::offset(9000)->limit(3000)->get();
    foreach ($bookings as $booking) {
        if($booking->supplierBooking){
            $rate = $booking->supplierBooking->rate;
            $lastRate = $rate;
        } else {
            $rate = $lastRate;
        }

        $amount = $faker->randomFloat(3, 10, 10000);
        $localAmount = $amount * (1/$rate);
        $bia = $localAmount + ($localAmount * 0.02);

        $booking->rate = $rate;
        $booking->account_name = $faker->company;
        $booking->account_num = $faker->bothify('###################');
        $booking->amount = $amount;
        $booking->rmb_book_amount = $amount;
        $booking->bia = $bia;
        $booking->save();

        if($booking->userBankSlip){
            $userBankSlip = $booking->userBankSlip;
            $userBankSlip->transfer_amount = $bia;
            $userBankSlip->save();
        }

        if($booking->invoice){
            foreach ($booking->invoice->invoiceDetails as $item ) {
                $amount = $faker->randomFloat(3, 10, 1000);
                $item->unit_price_rmb = $amount;
                $item->unit_price_rm =  $amount * (1/$rate);
            }
            $userBankSlip = $booking->userBankSlip;
            $userBankSlip->transfer_amount = $bia;
            $userBankSlip->save();
        }

        if($booking->chinaBankSlip()->exists()){
            $chinaBankSlip = $booking->chinaBankSlip()->first();
            $chinaBankSlip->actual_transfer_amount = $amount;
            $chinaBankSlip->save();
        }

        if($booking->supplierBooking){
            $supplierBooking = $booking->supplierBooking;
            $supplierBooking->rate = $rate;
            $supplierBooking->amountInRMB = $amount;
            $supplierBooking->amount_in_myr = $localAmount;
            $supplierBooking->amount_after_tax = $localAmount;

        }

        $bookingRate = $booking->rates;
        $bookingRate->x1_cash = $rate;
        $bookingRate->x1_cheque = $rate;
        $bookingRate->x1_ba = $rate;
        $bookingRate->x2_cash = $rate;
        $bookingRate->x2_cheque = $rate;
        $bookingRate->x2_ba = $rate;
        $bookingRate->save();
    }

    DB::commit();
})->name('bookings');
Route::group(['middleware' => ['role:admin']], function() {
    Route::get('/report/x1', function(){
        $bookings = Booking::where('admin_status', '>=', 3)->where('term', 'like', 'x1_%')->where('is_cancel', false)->where('user_id', '!=', 1)->get();
        echo "<h1 style='color: green;'>Total: ".$bookings->sum('bia')."</h1>";
        $months = $bookings->groupBy(function($item) {
            return $item->created_at->format('Y-m');
        });
        foreach($months as $month => $bookings){
            $newCustomers = \App\User::whereYear('created_at', '=', Carbon::parse($month)->format('Y')) ->whereMonth('created_at', '=', Carbon::parse($month)->format('m'))->get();
            echo "<h1>".Carbon::parse($month)->format('m-Y').": <small style='color: green; font-size: larger'>".$bookings->sum('bia')." MYR</small></h1>";
            echo "<h3>New Customer: <small style='color: green; font-size: larger'>".count($newCustomers)." Customers</small></h3>";
            echo "<h3>Active Customers: <small style='color: green; font-size: larger'>".count($bookings->groupBy(function($item){
                    return $item->user_id;
                }))." Customers</small></h3>";
            $days = $bookings->groupBy(function($item){
                return $item->created_at->format('Y-m-d');
            });

            foreach($days as $day => $bookings ){
                echo "<p>".Carbon::parse($day)->format('d-m-Y').": <small style='color: green; font-size: large'>".$bookings->sum('bia')." MYR</small></p>";
            }

        }

    });

    Route::get('/report/x2', function(){

        $bookings = Booking::where('admin_status', '>=', 3)->where('term', 'like', 'x2_%')->where('is_cancel', false)->where('user_id', '!=', 1)->get();
        echo "<h1 style='color: green;'>Total: ".$bookings->sum('bia')."</h1>";
        $months = $bookings->groupBy(function($item) {
            return $item->created_at->format('Y-m');
        });

        foreach($months as $month => $bookings){
            $newCustomers = \App\User::whereYear('created_at', '=', Carbon::parse($month)->format('Y')) ->whereMonth('created_at', '=', Carbon::parse($month)->format('m'))->get();
            echo "<h1>".Carbon::parse($month)->format('m-Y').": <small style='color: green; font-size: larger'>".$bookings->sum('bia')." MYR</small></h1>";
            echo "<h3>New Customer: <small style='color: green; font-size: larger'>".count($newCustomers)." Customers</small></h3>";
            echo "<h3>Active Customers: <small style='color: green; font-size: larger'>".count($bookings->groupBy(function($item){
                    return $item->user_id;
            }))." Customers</small></h3>";
            $days = $bookings->groupBy(function($item){
                return $item->created_at->format('Y-m-d');
            });

            foreach($days as $day => $bookings ){
                echo "<p>".Carbon::parse($day)->format('d-m-Y').": <small style='color: green; font-size: large'>".$bookings->sum('bia')." MYR</small></p>";
            }

        }

    });

    Route::get('/po-approval', function(){
        $approvedInvoices = InvoiceStatuses::where('status', 'approve')->distinct()->get(['invoice_id'])->pluck('invoice_id');
        $pendingChangeInvoices = InvoiceStatuses::where('status', 'request_change')->distinct()->get(['invoice_id'])->pluck('invoice_id');
        $invoices = InvoiceStatuses::whereNotIn('invoice_id', $approvedInvoices)->whereNotIn('invoice_id', $pendingChangeInvoices)->get();
        echo "<h1>Total PO Pending Approval: <b>".count($invoices)."</b></h1>";
        foreach ($invoices as $invoice){
            echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$invoice->invoice->booking->id."/upload-invoice'>".$invoice->invoice->booking->id."</a><br>";
        }

        $bookings = Booking::where('admin_status', 6)->where(function($q){
            $q->WhereDoesntHave('invoice')->WhereDoesntHave('purchaseOrder');
        })->get();
        $months = $bookings->groupBy(function($item) {
            return $item->created_at->format('Y-m');
        });
        echo "<h1>Total Po Pending Customer Update: <b>".count($bookings)."</b></h1>";
        foreach ($months as $month => $bookings) {
            echo "<h3>".$month."(".count($bookings).")</h3><br>";
            foreach ($bookings as $booking) {
                echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$booking->id."/upload-invoice'>".$booking->id."</a>     <small style='color: red;'>".$booking->user->marking."</small>   /   <small style='color: darkgrey;'>".$booking->created_at."</small><br>";
            }
            echo "<br><br><br>";
        }

    })->name('po.approval');

    Route::get('/po-pending-customers', function(){
        $bookings = Booking::where('admin_status', 6)->where(function($q){
            $q->WhereDoesntHave('invoice')->WhereDoesntHave('purchaseOrder');
        })->whereYear('created_at', '>=', 2020)->whereMonth('created_at', '>=', 4)->get();

        $customers = $bookings->groupBy(function($item) {
            return $item->user_id;
        })->sortByDesc(function($item){
            return count($item);
        }, SORT_NUMERIC);
        echo "<h1>Total Customers: <b>".count($customers)."</b></h1>";
        echo "<h1>Total Po Pending Customer Update: <b>".count($bookings)."</b></h1>";
        foreach ($customers as $customer => $bookings) {
            $i = 0;
            echo "<h3>".$bookings[0]->user->marking."(".count($bookings).")</h3><br>";
            foreach ($bookings as $booking) {
                $i += 1;
                echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$booking->id."/upload-invoice'>".$booking->id."</a>   /   <small style='color: darkgrey;'>".$booking->created_at."</small> <small style='color: dodgerblue;' href=''>https://exchange.cief-malaysia.com/booking/". $booking->id . "/upload-po</small><br>";
                if($i % 10 == 0) echo "<br><br>";
            }
            echo "<br><br><br>";
        }

    })->name('po.approval.customer');

    Route::get('/po-approved', function(){
        $approvedInvoices = InvoiceStatuses::where('status', 'approve')->distinct()->get(['invoice_id'])->pluck('invoice_id');
        $oldCompletedInvoices = Invoice::where('invoice_path', '!=', '')->orWhereNotNull('invoice_path')->get();
        $newCompletedInvoices = Invoice::whereIn('id', $approvedInvoices)->get();
        $total = count($oldCompletedInvoices) + count($newCompletedInvoices);
        echo "<h1>Total Po Approved: <b>".$total."</b></h1>";
        foreach ($newCompletedInvoices as $invoice){
            echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$invoice->booking->id."/admin/complete'>".$invoice->booking->id."</a> - ". $invoice->booking->bia."- <a target='_blank' href='https://exchange.cief-malaysia.com/admin/".$invoice->booking->user->id."/userBookings'>".$invoice->booking->user->marking."</a><br>";
        }
        foreach ($oldCompletedInvoices as $invoice){
            echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$invoice->booking->id."/admin/complete'>".$invoice->booking->id."</a> - ". $invoice->booking->bia." - <a target='_blank' href='https://exchange.cief-malaysia.com/admin/".$invoice->booking->user->id."/userBookings'>".$invoice->booking->user->marking."</a><br>";
        }
    })->name('po.approved');

    Route::get('/old-invoices', function(){

        $bookings = \App\Booking::where('status', 6)->where('user_id', '!=', 1)->whereHas('purchaseOrder', function($q){
            $q->whereNotNull('image_path');
        })->get();
        $months = $bookings->groupBy(function($item) {
            return $item->created_at->format('Y-m');
        });
        echo "<h1>Total pending invoices:<b>".count($bookings)."</b></h1>";
        foreach ($months as $month => $bookings) {
            echo "<h3>".$month."(".count($bookings).")</h3><br>";
            foreach ($bookings as $booking) {
                echo "<a target='_blank' href='https://exchange.cief-malaysia.com/booking/".$booking->id."/upload-invoice'>".$booking->id."</a> <small>date: ".$booking->created_at."</small><br>";
            }
            echo "<br><br><br>";
        }
    })->name('invoice.old');
});


Route::group(['middleware' => ['role:admin']], function() {
    Route::get('bulkBookings', function () {
        return view('booking.bulkBooking');
    })->name('booking.bulk.form');
    Route::post('/bulkBookings', 'BulkBookingController@index')->name('booking.bulk');
});
Route::get('{path}', 'WelcomeController@index')->where('path', '(.*)');
Auth::routes();

//Route::get('/home', 'WelcomeController@index')->name('home');
