<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use App\Models\EmailDraft;
use Illuminate\Foundation\Auth\User as Authenticatable;
use DB;
use Carbon\Carbon;

class User extends Authenticatable
{
    use HasFactory, Notifiable;
    protected $table = "users";
    public $timestamps = false;


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'Email',
        'password',
        'CustomerName'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function fetchAllUsers()
    {
        $result = User::where('is_delete', '!=', 'true')->where('CustomerID', '!=', '111111')->orderBy('CustomerID', 'desc');
        $authAdmin = auth()->user();
        if ($authAdmin->type == 'sub-admin') {
            $divisionIds = AssignDivisionAdmin::where('admin_id', $authAdmin->id)->pluck('division_id')->toArray();
            $divisionTeamMemberIds = AssignDivisionTeamMember::whereIn('division_id', $divisionIds)->pluck('customer_id')->toArray();
            $result = $result->whereIn('CustomerID', $divisionTeamMemberIds);
        }
        return $result;
    }

    public function fetchAllUsers2($search = null)
    {
        $result = User::where('CustomerID', '!=', '111111')->orderBy('CustomerID', 'desc');
        $authAdmin = auth()->user();
        if ($authAdmin->type == 'sub-admin') {
            $divisionIds = AssignDivisionAdmin::where('admin_id', $authAdmin->id)->pluck('division_id')->toArray();
            $divisionTeamMemberIds = AssignDivisionTeamMember::whereIn('division_id', $divisionIds)->pluck('customer_id')->toArray();
            $result = $result->whereIn('CustomerID', $divisionTeamMemberIds);
        }
        $result->when($search,function($q)use($search){
            $q->where(function($q)use($search){
                $q->where('CustomerName','like','%'.$search.'%')->orWhere('Phone','like','%'.$search.'%')->orWhere('Email','like','%'.$search.'%');
                if(intval($search) != 0){
                    $q->orWhere("CustomerID",$search);
                }
            });
        });
        return $result;
    }

    public static function countUsers()
    {
        $result = User::where('CustomerID', '!=', '111111')->where('is_delete', '!=', 'true');
        $authAdmin = auth()->user();
        if ($authAdmin->type == 'sub-admin') {
            $divisionIds = AssignDivisionAdmin::where('admin_id', $authAdmin->id)->pluck('division_id')->toArray();
            $divisionTeamMemberIds = AssignDivisionTeamMember::whereIn('division_id', $divisionIds)->pluck('customer_id')->toArray();
            $result = $result->whereIn('CustomerID', $divisionTeamMemberIds);
        }
        return $result->count();
    }

    public static function countUsers2()
    {
        $result = User::where('CustomerID', '!=', '111111')->get();
        $authAdmin = auth()->user();
        if ($authAdmin->type == 'sub-admin') {
            $divisionIds = AssignDivisionAdmin::where('admin_id', $authAdmin->id)->pluck('division_id')->toArray();
            $divisionTeamMemberIds = AssignDivisionTeamMember::whereIn('division_id', $divisionIds)->pluck('customer_id')->toArray();
            $result = $result->whereIn('CustomerID', $divisionTeamMemberIds);
        }
        return $result->count();
    }

    public function primaryEmail()
    {
        return $this->hasOne(EmailDraft::class, 'primary_email');
    }

    public function followUpEmail()
    {
        return $this->hasOne(EmailDraft::class, 'follow_up_email');
    }
    public static function insert_user_with_martkey($type, $indiamartkey, $event_id = '')
    {
        if ($type == 'india_mart') {
            $key = 'IndiaMart';
        } else {
            $key = 'TradIndia';
        }


        $data = [
            'CustomerID' => "1111111",
            'status' => "true",
            'datetime' => date('Y-m-d H:i:s'),
            'expiry_date' => date('Y-m-d H:i:s'),
            'google_drive' => "false",
            'email_service' => "false",
            'Notes' => "na",
            'CustomerName' => $key,
            'Phone' => "na",
            'Email' => "na",
            'CompanyName' => "na",
            'sender_name' => NULL,
            'sender_email' => NULL,
            'cc_email' => NULL,
            'follow_up_email' => NULL,
            'primary_email' => NULL,
            'Location' => "na",
            'device_type' => "na",
            'app_version' => "1",
            'version_code' => "0",
            'android_version' => "0",
            'device_model' => "0",
            'push_token' => "na",
            'code' => $key,
            'is_admin' => "false",
            'is_delete' => "false",
        ];

        $user = DB::table('users')->where('CustomerID', $data['CustomerID'])->first();

        if (!$user) {
            $user_id = DB::table('users')->insertGetId($data);
        } else {
            $user_id =  $user->user_id;
        }

        if (!empty($event_id)) {
            $getAdminUsersIds =  DB::table('users')->where('is_admin', 'true')->pluck('user_id')->toArray();
            if (count($getAdminUsersIds) > 0) {
                foreach ($getAdminUsersIds as $userId) {
                    $event_data = [
                        'fk_user_id' => $userId,
                        'fk_event_id' => $event_id,
                        'is_admin' => 'true',
                        'created_date' => Carbon::now('Asia/Kolkata')
                    ];
                    DB::table('event_assignments')->insert($event_data);
                }
            }
        }

        return $user_id;
    }
}
