<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Models\Appointment;
use App\Models\Leadhistory;
use App\Models\Leads;
use App\Models\Leadstatus;
use App\Models\Mtaccount;
use App\Models\Product;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Facades\Excel;

class AffiliateController extends Controller
{
    public function messages()
    {
        return [
            'newpassword.required' => 'password required',
        ];
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        if (Auth::user()->affiliate == '1') {
            $accounts = User::where('afid', Auth::user()->id)->get();
            return view('admin.affiliate.index', compact('accounts'));
        } else {
            abort(403);
        }
    }

    public function leadindex()
    {
        //  dd("in");
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            /*$accounts = DB::table('leads')
            ->join('users', 'leads.leadowner', '=', 'users.id')
            ->select('users.name','users.email','leads.*')
            ->get();*/
            $accounts =  Leads::orderBy('id', 'DESC')->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            /* $accounts = DB::table('leads')
            ->join('users', 'leads.leadowner', '=', 'users.id')
            ->select('users.name','users.email','leads.*')
			->where('leads.leadowner',Auth::user()->id)
            ->get();*/
            $accounts = Leads::where('leadowner', Auth::user()->id)->orderBy('id', 'DESC')->get();
        } elseif ($checkadmin == false && Auth::user()->issubadmin == '1') {
            /* $accounts = DB::table('leads')
            ->join('users', 'leads.leadowner', '=', 'users.id')
            ->select('users.name','users.email','leads.*')
			->where('leads.leadowner',Auth::user()->id)
            ->get();*/
            $accounts = Leads::where('leadowner', Auth::user()->id)->orderBy('id', 'DESC')->get();
        } else {
            abort(403);
        }

        if (Auth::user()->affiliate == '1' && Auth::user()->issubadmin == '1') {

            $getafids = User::select('id')->where('afid', Auth::user()->id)->pluck('id')->toArray();
            $afids = array_merge($getafids, $getafids);
            // dd($afids);
            $accounts = Leads::whereIn('leadowner', $afids)->orderBy('id', 'DESC')->get();
        }
        return view('admin.affiliate.leadindex', compact('accounts'));
    }

    public function leadhist($id)
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            /*$accounts = DB::table('leads')
            ->join('users', 'leads.leadowner', '=', 'users.id')
            ->select('users.name','users.email','leads.*')
            ->get();*/
            $accounts = Leadhistory::where('leadid', $id)->orderBy('id', 'DESC')->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            /* $accounts = DB::table('leads')
            ->join('users', 'leads.leadowner', '=', 'users.id')
            ->select('users.name','users.email','leads.*')
			->where('leads.leadowner',Auth::user()->id)
            ->get();*/
            //$accounts = Leadhistory::where('id',$id)->orderBy('id','DESC')->get();
            $accounts = Leadhistory::where('leadid', $id)->where('leadowner', Auth::user()->id)->orderBy('id', 'DESC')->get();
        } else {
            abort(403);
        }


        return view('admin.affiliate.leadindexstatus', compact('accounts'));
    }

    public function createleads()
    {
        abort_unless(Gate::allows('permission_create'), 403);
        $countries = DB::table('countries')->get();
        $accounts = User::where('affiliate', '1')->get();
        $leadstatus = Leadstatus::all();
        return view('admin.affiliate.leadcreate', compact('accounts','countries','leadstatus'));
    }

    public function leadsedit($id)
    {
        // abort_unless(\Gate::allows('permission_create'), 403);
        $accounts = User::where('affiliate', '1')->get();
        $leaddata = Leads::where('id', $id)->first();
        $leadstatus = Leadstatus::all();
        return view('admin.affiliate.leadsedit', compact('accounts', 'id', 'leaddata','leadstatus'));
    }

    public function leadsupdate(Request $request)
    {
        //  abort_unless(\Gate::allows('permission_create'), 403);
        $validator = Validator::make($request->all(), [
            'email' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        Leads::where('id', $request->id)->update(array(
            'email'     => $request->email,
            'status'     => $request->status,
            'leadowner' => $request->leadowner,
            'note' => $request->note
        ));

        Leadhistory::create(array(
            'leadid'     => $request->id,
            'email'     => $request->email,
            'status'     => $request->status,
            'leadowner' => $request->leadowner,
            'note' => $request->note
        ));

        User::where('email', $request->email)->update(array(
            'afid' => $request->leadowner
        ));
        return redirect('admin/leads')->with('success', 'Lead updated successfully');
    }

    public function storeleads(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstname' => 'required',
            'lastname' => 'required',
            'email' => 'required',
            'country' => 'required',
            'mobile' => 'required',
            'source' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $request->all();
        $adduser = array();
        // echo '<pre>';print_r($data);exit;

        Leads::create($data);

        return redirect('admin/leads')->with('success', 'Lead created successfully');
    }

    public function storeAppointment(Request $request)
    {
        // Validate the input
        $request->validate([
            'lead_id' => 'required|exists:leads,id',
            'appointment_description' => 'required|string|max:255',
            'appointment_date' => 'required|date',
            'appointment_time' => 'required|date_format:H:i',
        ]);

        $appointment = new Appointment();
        $appointment->lead_id = $request->input('lead_id');
        $appointment->appointment_note = $request->input('appointment_description');
        $appointment->appointment_date = $request->input('appointment_date');
        $appointment->appointment_time = $request->input('appointment_time');
        // echo '<pre>';print_r($appointment);exit;

        $appointment->save();

        return redirect()->back()->with('success', 'Appointment added successfully.');
    }

    public function calendar()
    {
        return view('admin.affiliate.calender');
    }

    public function getAppointments(Request $request)
    {
        $appointments = Appointment::all();

        $events = [];

        foreach ($appointments as $appointment) {
            $start = Carbon::parse($appointment->appointment_date . ' ' . $appointment->appointment_time)->format('Y-m-d\TH:i:s');
            $end = Carbon::parse($appointment->appointment_date . ' ' . $appointment->appointment_time)->addMinutes(30)->format('Y-m-d\TH:i:s');

            $events[] = [
                'title' => $appointment->appointment_note . ' (' . date('h:i A', strtotime($appointment->appointment_time)) . ')',
                'start' => $start,
                'end' => $end,
                'allDay' => false,
                'backgroundColor' => 'rgba(58,87,232,0.2)',
                'textColor' => 'rgba(58,87,232,1)',
                'borderColor' => 'rgba(58,87,232,1)',
            ];
        }

        return response()->json($events);
    }

    public function myclientaccounts()
    {
        //abort_unless(\Gate::allows('user_client'), 403);
        if (Auth::user()->affiliate == '1') {

            $accounts = DB::table('mtaccount')
                ->join('users', 'mtaccount.userid', '=', 'users.id')
                ->select('users.name', 'users.afid', 'users.email', 'users.mobile', 'mtaccount.id', 'mtaccount.loginid', 'mtaccount.mainpass', 'mtaccount.groupname', 'mtaccount.created_at')
                ->where('users.afid', Auth::user()->id)
                ->get();
            return view('admin.affiliate.mymtaccount', compact('accounts'));
        } else {
            abort(403);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        abort_unless(Gate::allows('user_client'), 403);

        return view('admin.mtaccount.create');
    }

    public function changemt4password()
    {
        abort_unless(Gate::allows('user_client'), 403);
        $myaccounts = Mtaccount::where('userid', Auth::user()->id)->get();
        return view('admin.mtaccount.changepass', compact('myaccounts'));
    }

    public function storemt4pass(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'newpassword' => 'required|string|min:8|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $request->all();
        $adduser = array();

        Mtaccount::where('loginid', $request->mt4account)->update(array(
            'mainpass'     => $request->newpassword,
        ));
        return redirect()->back()->with('success', 'Your mt4 account password change successfully.');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        abort_unless(Gate::allows('user_client'), 403);
        $data = $request->all();
        $adduser = array();
        $fourRandomDigit = mt_rand(1000, 9999);
        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $uniqpass = substr(str_shuffle($str_result), 0, 8);

        $adduser['userid'] = Auth::user()->id;
        $adduser['loginid'] = $fourRandomDigit;
        $adduser['mainpass'] = $uniqpass;
        $adduser['leverage'] = $data['leverage'];
        $adduser['groupname'] = $data['groupname'];

        $product = Mtaccount    ::create($adduser);

        return redirect()->route('admin.mtaccount.index');
    }

    /**
     * Display the specified resource.
     */
    public function show(Product $product)
    {
        abort_unless(Gate::allows('product_show'), 403);

        return view('admin.products.show', compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Product $product)
    {
        //  abort_unless(\Gate::allows('product_edit'), 403);

        return view('admin.products.edit', compact('product'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateProductRequest $request, Product $product)
    {
        // abort_unless(\Gate::allows('product_edit'), 403);

        $product->update($request->all());

        return redirect()->route('admin.products.index');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Product $product)
    {
        abort_unless(Gate::allows('product_delete'), 403);

        $product->delete();

        return back();
    }

    public function massDestroy(MassDestroyProductRequest $request)
    {
        Product::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }

    public function leadsbulk()
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            $accounts = User::where('affiliate', '1')->get();
            $leaddata = Leads::get();
        } else {
            abort(403);
        }
        return view('admin.affiliate.leadsbulk', compact('accounts', 'leaddata'));
    }

    public function exportLeads()
    {
        $leadData = Leads::all();

        return Excel::download(new class($leadData) implements FromArray, WithHeadings {
            private $leadData;

            public function __construct($leadData)
            {
                $this->leadData = $leadData;
            }

            public function array(): array
            {
                return $this->leadData->map(function ($lead) {
                    return [
                        $lead->firstname,
                        $lead->lastname,
                        $lead->email,
                        $lead->country,
                        $lead->mobile,
                        $lead->source,
                        $lead->sourceurl,
                        $lead->status,
                    ];
                })->toArray();
            }

            public function headings(): array
            {
                return [
                    'First Name', 'Last Name', 'Email', 'Country', 'Mobile', 'Source', 'Source URL', 'Status',
                ];
            }
        }, 'Leads.xlsx');
    }
}
