<?php

namespace App\Http\Controllers\Setting;

use DataTables;
use Carbon\Carbon;
use App\Models\Bank;
use App\Models\User;
use App\Models\Order;
use App\Models\State;
use App\Models\Package;
use App\Models\Affiliate;
use App\Models\LogReport;
use App\Models\UserDetail;
use Illuminate\Support\Str;
use App\Models\Notification;
use App\Models\OrderHistory;
use App\Models\OrderPackage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;

class AgentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if(Auth::user()->getRoleNames()->implode(',') == 'agent')
        {
            
            $data = Affiliate::where('parent', Auth::user()->id)->get();
            if ($request->ajax()) {
                return Datatables::of($data)
                ->addIndexColumn()   
                ->addColumn('user', 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('role', function($data){
                    return '<span class="badge badge-primary">'.ucfirst($data->user->getRoleNames()->implode(',')).'</span>';
                })      
                ->addColumn('status', function($data){

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

                    return '    

                        <a href="'.route('edit-agent', $data->user->id).'" class="btn btn-sm btn-light btn-icon btn-hover-success mr-2" title="Edit details">
                            <span class="svg-icon svg-icon-md svg-icon-success">
                                <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="M8,17.9148182 L8,5.96685884 C8,5.56391781 8.16211443,5.17792052 8.44982609,4.89581508 L10.965708,2.42895648 C11.5426798,1.86322723 12.4640974,1.85620921 13.0496196,2.41308426 L15.5337377,4.77566479 C15.8314604,5.0588212 16,5.45170806 16,5.86258077 L16,17.9148182 C16,18.7432453 15.3284271,19.4148182 14.5,19.4148182 L9.5,19.4148182 C8.67157288,19.4148182 8,18.7432453 8,17.9148182 Z" fill="#000000" fill-rule="nonzero"\ transform="translate(12.000000, 10.707409) rotate(-135.000000) translate(-12.000000, -10.707409) "/>
                                        <rect fill="#000000" opacity="0.3" x="5" y="20" width="15" height="2" rx="1"/>
                                    </g>
                                </svg>
                            </span>
                        </a>
                        
                        <a href="'.route('show-agent', $data->user->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);
            } 
        }
        else
        {
            $data = User::role('agent')->get();
       
        

            if ($request->ajax()) {
                return Datatables::of($data)
                ->addIndexColumn()   
                ->addColumn('user', 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->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->name.'</span>
                                    <!--end::Title-->
                                </div>
                            </div>';
                    
                })    
                ->addColumn('role', function($data){
                    return '<span class="badge badge-primary">'.ucfirst($data->getRoleNames()->implode(',')).'</span>';
                })      
                ->addColumn('status', function($data){

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

                    return '    

                        <a href="'.route('edit-agent', $data->id).'" class="btn btn-sm btn-light btn-icon btn-hover-success mr-2" title="Edit details">
                            <span class="svg-icon svg-icon-md svg-icon-success">
                                <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="M8,17.9148182 L8,5.96685884 C8,5.56391781 8.16211443,5.17792052 8.44982609,4.89581508 L10.965708,2.42895648 C11.5426798,1.86322723 12.4640974,1.85620921 13.0496196,2.41308426 L15.5337377,4.77566479 C15.8314604,5.0588212 16,5.45170806 16,5.86258077 L16,17.9148182 C16,18.7432453 15.3284271,19.4148182 14.5,19.4148182 L9.5,19.4148182 C8.67157288,19.4148182 8,18.7432453 8,17.9148182 Z" fill="#000000" fill-rule="nonzero"\ transform="translate(12.000000, 10.707409) rotate(-135.000000) translate(-12.000000, -10.707409) "/>
                                        <rect fill="#000000" opacity="0.3" x="5" y="20" width="15" height="2" rx="1"/>
                                    </g>
                                </svg>
                            </span>
                        </a>
                        
                        <a href="'.route('show-agent', $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('setting.agent.index'); 
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $states = State::all();
        $banks = Bank::all();
        $packages = Package::all();

        return view('setting.agent.create', [
            'states' => $states,
            'banks' => $banks,
            'packages' => $packages
        ]); 
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $val_data = $request->validate([
            'role' => 'required',
            'name' => 'required',
            'nric_number' => 'required',
            'phone_number' => 'required',
            'email' => 'required|email|unique:users,email',
            'introducer_id' => 'required',
            'package' => 'required',
        ]);

        $user = User::create([
            'name' => $request->name,
            'nric_number' => $request->nric_number,
            'phone_number' => $request->phone_number,
            'email' =>$request->email,
            'username' => $request->nric_number,
            'password' =>Hash::make($request->password),
            'introducer_id' => random_int(100000, 999999),
            'package_id' => $request->package,
            'user_status_id' => 1,
            'avatar' => 'blank.png'
        ]);

        UserDetail::create([
            'user_id' => $user->id,
            'bank_id' => 1,
            'address' =>$request->address,
            'postcode' =>$request->postcode,
            'city' =>$request->city,
            'state' =>$request->state
        ]);

        $user->assignRole($request->role);

        $parent = User::where('introducer_id', $request->introducer_id)->get();

        Affiliate::create([
            'parent' => $parent[0]->id,
            'user_id' => $user->id,
        ]); 

        $token = Str::random(64);

        DB::table('password_resets')->insert([
            'email' => $request->email, 
            'token' => $token, 
            'created_at' => Carbon::now()
        ]);

        $data = array(
            'token' => $token,
            'username' => $request->name,
            'id' => $user->id
        );
            
        Mail::send('mail.first-login', $data, function($message) use($request){
            $message->to($request->email);
            $message->subject('Setup Your Account');
        });

        // ------ CREATE ORDER -------

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

        $order = Order::create([
            'code'=> generateRandomString(),
            'order_status_id' => 1,
            'user_id' => $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' => $user->user,
            'email' => $user->email,
            'order' => $order,
            'text1' => 'Thank you for your purchase!',
            'text2' => 'Please make payment within 48 hour.'
        );

        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' => Auth::user()->username,
            'email' => Auth::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 redirect()->route('index-agent')->with('success', 'Registration Successfully!');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $agent = User::findorfail($id);
        $packages = Package::all();
        $order = Order::where('user_id', $id)->first();

        $parent_id = Affiliate::where('user_id', $id)->select('parent')->get();

        $parent = User::findorfail($parent_id);

        $downlines = Affiliate::where('parent', $id)->get();

        return view('setting.agent.detail', [
            'agent' => $agent,
            'packages' => $packages,
            'order' => $order,
            'parent' => $parent,
            'downlines' => $downlines
        ]); 
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = User::findorfail($id);

        $states = State::all();
        $banks = Bank::all();
        $packages = Package::all();

        return view('setting.agent.edit', [
            'states' => $states,
            'banks' => $banks,
            'user' => $user,
            'packages' => $packages
        ]); 
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {   $user = User::findorfail($id);

        if($user->email ==  $request->email)
        {
            $val_data = $request->validate([
                //'role' => 'required',
                'name' => 'required',
                'nric_number' => 'required',
                'phone_number' => 'required',
                'email' => 'required'
            ]);
        }
        else{
            $val_data = $request->validate([
                //'role' => 'required',
                'name' => 'required',
                'nric_number' => 'required',
                'phone_number' => 'required',
                'email' => 'required|email|unique:users,email'
            ]);
        }

        

        /* if($request->role != $user->getRoleNames()->implode(',') )
        {
            DB::table('model_has_roles')->where('model_id',$id)->delete();
            $user->assignRole($request->role); 
        } */

        $user = User::where('id', $id)
        ->update([
            'name' => $request->name,
            'nric_number' => $request->nric_number,
            'phone_number' => $request->phone_number,
            'email' =>$request->email,
        ]);

        UserDetail::where('user_id', $id)
        ->update([
            'address' =>$request->address,
            'postcode' =>$request->postcode,
            'city' =>$request->city,
            'state' =>$request->state
        ]);

        return back()->with('success', 'Agent profile has been updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
