<?php

namespace App\Http\Controllers\Order;

use DataTables;
use App\Models\User;
use App\Models\Order;
use App\Models\Package;
use App\Models\LogReport;
use App\Models\Notification;
use App\Models\OrderHistory;
use App\Models\OrderPackage;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\OrderStatus;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        session()->forget('reselect_package');

        $statuses = OrderStatus::all();

        $data = Order::all();

        if ($request->ajax()) {
            return Datatables::of($data)
                ->addIndexColumn()   
                ->addColumn('no', function($data){

                    return '<div class="form-check form-check-sm form-check-custom form-check-solid">
                                <input class="form-check-input" type="checkbox" value="'.$data->id.'" />
                            </div>';
                })  
                ->addColumn('order_id', function($data){

                    return ' <span class="text-gray-800 text-hover-primary fw-bold">'.$data->code.'</span>';
                })    
                ->addColumn('agent', function($data){
                            
                    return '<div class="d-flex align-items-center">
                                <!--begin:: Avatar -->
                                <div class="symbol symbol-circle symbol-50px overflow-hidden">
                                    <a href="javascript:void(0);">
                                        <div class="symbol-label">
                                            <img src="'.asset('media/avatars/'.$data->user->avatar) .'" class="w-100" />
                                        </div>
                                    </a>
                                </div>
                                <!--end::Avatar-->
                                <div class="ms-5">
                                    <!--begin::Title-->
                                    <span class="text-gray-800 text-hover-primary fs-5 fw-bold">'.$data->user->name.'</span>
                                    <!--end::Title-->
                                </div>
                            </div>';
                    
                }) 
                ->addColumn('status', function($data){

                    return '<div class="badge badge-light-'.$data->order_status->color.'">'.$data->order_status->name.'</div>';
                
                })  
                ->addColumn('total', function($data){

                    return '<span class="fw-bold">RM '.$data->total_rm.'</span>';
                })  
                ->addColumn('date_added', function($data){

                    return '<span class="fw-bold">'.date('d/m/Y', strtotime($data->created_at)).'</span>';
           
                })          
                ->addColumn('action', function($data) {


                        return '

                        <a href="'.route('show-order', $data->id).'" class="btn btn-sm btn-light btn-icon btn-hover-light mr-2 " title="View">
                            <span class="svg-icon svg-icon-primary svg-icon-2x"><!--begin::Svg Icon | path:/var/www/preview.keenthemes.com/metronic/releases/2021-05-14-112058/theme/html/demo1/dist/../src/media/svg/icons/General/Visible.svg--><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1">
                                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                                    <rect x="0" y="0" width="24" height="24"/>
                                    <path d="M3,12 C3,12 5.45454545,6 12,6 C16.9090909,6 21,12 21,12 C21,12 16.9090909,18 12,18 C5.45454545,18 3,12 3,12 Z" fill="#000000" fill-rule="nonzero" opacity="0.3"/>
                                    <path d="M12,15 C10.3431458,15 9,13.6568542 9,12 C9,10.3431458 10.3431458,9 12,9 C13.6568542,9 15,10.3431458 15,12 C15,13.6568542 13.6568542,15 12,15 Z" fill="#000000" opacity="0.3"/>
                                </g>
                            </svg><!--end::Svg Icon--></span>
                
                        </a>';
                    

                    
                })
                ->escapeColumns([])
                //->rawColumns(['action'])
                ->make(true);
        } 

        return view('order.index',[
            'statuses' => $statuses
        ]); 
    }

    public function show($id)
    {
        $order = Order::findorfail($id);

        return view('order.show', [
            'order' => $order,
        ]); 
    }
    
    public function edit($id)
    {
        $order = Order::findorfail($id);
        $packages  = Package::all();

        $reselect_package = $order->order_packages[0]->package_id;
        if(session()->has('reselect_package'))
        {
            $reselect_package = session()->get('reselect_package');
        }

        return view('order.edit-reselect-package', [
            'order' => $order,
            'packages' => $packages,
            'reselect_package' => $reselect_package
        ]); 
    }

    public function next(Request $request, $id)
    {
        $request->session()->put('reselect_package', $request->package);

        return response()->json(['success'=> '1', 'id' => $id]);
    }

    public function buy_package(Request $request)
    {

        $package = Package::findorfail($request->package);

        User::where('id',Auth::user()->id)
        ->update([
            'package_id' => $request->package
        ]);

        $order = Order::create([
            'code'=> generateRandomString(),
            'order_status_id' => 1,
            'user_id' => Auth::user()->id,
            'total_rm' => $package->ablv_rm
        ]);

        OrderPackage::create([
            'order_id' => $order->id,
            'package_id' => $request->package,
            'iso' => $package->iso,
            'position' => $package->position,
            'ablv_rm' => $package->ablv_rm,
            'shareholder_rm' => $package->shareholder_rm,
            'discount_percent' => $package->discount_percent,
            'contract' => $package->contract,
            'legal_fee_rm' => $package->legal_fee_rm,
        ]);

        OrderHistory::create([
            'order_id' => $order->id,
            'order_status_id' => 1,
            'notify' => 1,
            'comment' => 'Successfully submitted. Pending approval'
        ]);

        LogReport::create([
            'user_id' => Auth::user()->id,
            'module' => 'Order',
            'ref_id' => $order->id,
            'details' => Auth::user()->id.' submit order'
        ]); 

        Notification::create([
            'user_id' => 1,
            'reference_table' => 'orders',
            'reference_id' => $order->id,
            'module' => 'Order',
            'comment' => 'New order, approve this order',
            'status_name'=> 'Pending',
            'status_color' =>'warning'
        ]); 

        

        $data_agent = array(
            'name' => Auth::user()->username,
            'email' => Auth::user()->email,
            'order' => $order,
            'text1' => 'Thank you for your purchase!',
            'text2' => 'Please make payment sofdfsdf .....'
        );

        Mail::send('mail.new-order', $data_agent, function($message) use($data_agent){
            $message->to($data_agent['email']);
            $message->subject('New Order - '.$data_agent['order']->code);
        });

        $user = User::findorfail(1);

        $data_admin = array(
            'name' => $user->username,
            'email' => $user->email,
            'order' => $order,
            'text1' => 'New incoming order!',
            'text2' => 'You have new order, please approve the order'
        );

        Mail::send('mail.new-order', $data_admin, function($message) use($data_admin){
            $message->to($data_admin['email']);
            $message->subject('New Order - '.$data_admin['order']->code);
        });

        return response()->json(['success'=> 'Your package purchase was successful. Please submit payment first.']);
    }

    public function edit_payment($id)
    {
        $order = Order::findorfail($id);
        $packages  = Package::all();

        return view('order.edit-payment', [
            'order' => $order,
            'packages' => $packages,
        ]); 
    }

    public function approve(Request $request, $id)
    {
        $val_data = $request->validate([
            'payment_date' =>'required',
            'payment_method' =>'required',
            'amount_of_payment' =>'required',
            'abla' => 'required'
        ]);

        $order = Order::findorfail($id);

        $reselect_package = $order->order_packages[0]->package_id;
        if(session()->has('reselect_package'))
        {
            $reselect_package = session()->get('reselect_package');
        }

        User::where('id',$order->user_id)
        ->update([
            'user_status_id' => 2,
            'package_id' => $request->reselect_package
        ]);

        

        $package  = Package::findorfail($reselect_package);

        Order::where('id', $id)
        ->update([
            'order_status_id' => 2,
            'user_id' => Auth::user()->id,
            'total_rm' => $package->ablv_rm,
            'payment_method' => $request->payment_method,
            'payment_date' => date('Y-m-d', strtotime($request->payment_date)),
            'payment_comment' => $request->comment,
            'payment_amt_rm' => $request->amount_of_payment,
            'abla_amt' => $request->abla
        ]);

        if($reselect_package != $order->order_packages[0]->package_id)
        {
            OrderPackage::where('order_id', $id)->delete();

            OrderPackage::create([
                'order_id' => $order->id,
                'package_id' => $reselect_package,
                'iso' => $package->iso,
                'position' => $package->position,
                'ablv_rm' => $package->ablv_rm,
                'shareholder_rm' => $package->shareholder_rm,
                'discount_percent' => $package->discount_percent,
                'contract' => $package->contract,
                'legal_fee_rm' => $package->legal_fee_rm,
            ]);
        }


        OrderHistory::create([
            'order_id' => $id,
            'order_status_id' => 2,
            'notify' => 1,
            'comment' => 'The order has been approved.'
        ]);

        LogReport::create([
            'user_id' => Auth::user()->id,
            'module' => 'Order',
            'ref_id' => $id,
            'details' => Auth::user()->id.' approve order'
        ]); 

        Notification::create([
            'user_id' => $order->user_id,
            'reference_table' => 'orders',
            'reference_id' => $id,
            'module' => 'Order',
            'comment' => 'Your order has been approved',
            'status_name'=> 'Approved',
            'status_color' =>'success'
        ]); 

        

        $data = array(
            'name' => $order->user->username,
            'email' => $order->user->email,
            'order' => Order::findorfail($id),
            'text1' => 'Your order has been approved!',
            'text2' => ''
        );

        Mail::send('mail.new-order', $data, function($message) use($data){
            $message->to($data['email']);
            $message->subject('Order Status - '.$data['order']->code);
        });

        return response()->json(['success'=> 'Successfully approved', 'id' => $id]);
    }

    public function reject(Request $request, $id)
    {
        $val_data = $request->validate([
            'payment_date' =>'required',
            'payment_method' =>'required',
            'amount_of_payment' =>'required',
            'abla' => 'required'
        ]);

        $order = Order::findorfail($id);

        User::where('id',$order->user_id)
        ->update([
            'user_status_id' => 3
        ]);

        $reselect_package = $order->order_packages[0]->package_id;
        if(session()->has('reselect_package'))
        {
            $reselect_package = session()->get('reselect_package');
        }

        $package  = Package::findorfail($reselect_package);

        Order::where('id', $id)
        ->update([
            'order_status_id' => 3,
            'user_id' => Auth::user()->id,
            'total_rm' => $package->ablv_rm,
            'payment_method' => $request->payment_method,
            'payment_date' => date('Y-m-d', strtotime($request->payment_date)),
            'payment_comment' => $request->comment,
            'payment_amt_rm' => $request->amount_of_payment,
            'abla_amt' => $request->abla
        ]);

        if($reselect_package != $order->order_packages[0]->package_id)
        {
            OrderPackage::where('order_id', $id)->delete();

            OrderPackage::create([
                'order_id' => $order->id,
                'package_id' => $reselect_package,
                'iso' => $package->iso,
                'position' => $package->position,
                'ablv_rm' => $package->ablv_rm,
                'shareholder_rm' => $package->shareholder_rm,
                'discount_percent' => $package->discount_percent,
                'contract' => $package->contract,
                'legal_fee_rm' => $package->legal_fee_rm,
            ]);
        }


        OrderHistory::create([
            'order_id' => $id,
            'order_status_id' => 3,
            'notify' => 1,
            'comment' => 'The order has been rejected.'
        ]);

        LogReport::create([
            'user_id' => Auth::user()->id,
            'module' => 'Order',
            'ref_id' => $id,
            'details' => Auth::user()->id.' reject order'
        ]); 

        Notification::create([
            'user_id' => $order->user_id,
            'reference_table' => 'orders',
            'reference_id' => $id,
            'module' => 'Order',
            'comment' => 'Your order has been rejected',
            'status_name'=> 'Rejected',
            'status_color' =>'warning'
        ]); 

        

        $data = array(
            'name' => $order->user->username,
            'email' => $order->user->email,
            'order' => Order::findorfail($id),
            'text1' => 'Your order has been rejected!',
            'text2' => ''
        );

        Mail::send('mail.new-order', $data, function($message) use($data){
            $message->to($data['email']);
            $message->subject('Order Status - '.$data['order']->code);
        });

        return response()->json(['success'=> 'Successfully rejected', 'id' => $id]);
    }

}
