<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class SendEmailsOperatorController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    static function listVehicles()
    {
        $manager_id = env('MANAGER_ID');
        $B2L = env('B2L');
        $PVO = env('PVO');

        date_default_timezone_set('Europe/Paris');
        $datetime = strtotime('-' . env('DATE') . ' days');
        $date_prise_en_compte = date('Y-m-d H:i:s', $datetime);
        $datetime1 = strtotime('-1 days');
        $newdate = date('Y-m-d H:i:s', $datetime1);

        $list = DB::connection('mysql2')
        ->table("vehicules")
        ->Join("users", "vehicules.client_id", "=", "users.id")
        ->select(
            "vehicules.id",
            "accepted",
            "vehicules.name",
            "manager_id",
            "client_id",
            "users.id_bee2link",
            "id_client_bee2link",
            "statut_bee2link",
            "bee2link_sent",
            "users.id_pvo",
            "id_client_pvo",
            "vehicules.pvo_sent",
            "operator_id",
            "mail_sent_operator",
            "vehicules.created_at",
            "vehicules.updated_at"
        )
        ->where(function($query){
            $query->where("accepted", "=", 1)
                  ->where("vehicules.deleted_at", "=", NULL);
        })
        ->where(function($query){
            $query->where("pvo_sent", "=", NULL)
                  ->orWhere("bee2link_sent", "=", NULL);
        })
        ->where(function($query){
            $query->where("users.id_pvo", "!=", NULL)
                  ->orWhere("users.id_bee2link", "!=", NULL)
                  ->orWhere("vehicules.id_client_pvo", "!=", NULL)
                  ->orWhere("vehicules.id_client_bee2link", "!=", NULL);
        })
        ->where(function($query){
            $query->where("mail_sent_operator", "=", NULL)
                    ->orwhere("mail_sent_operator", "<", 3);
        })
        ->where("vehicules.updated_at", ">=", $date_prise_en_compte)
        ->orderBy("vehicules.updated_at", "desc");

        if($manager_id !== NULL)
        {
            $vehicles = $list->where('manager_id', '=', $manager_id)->get();
        }
        else
        {
           $vehicles = $list->get();
        }

        $trash = [];
        $filter_list = [];
        $list_vehicles = [];

        $pattern_immat_1 = "/^[A-Z]{2}[0-9]{3}[A-Z]{2}$/i";
        $pattern_immat_2 = "/^[A-Z]{2}[-][0-9]{3}[-][A-Z]{2}$/i";
        $pattern_immat_3 = "/^[A-Z]{2}[ ][0-9]{3}[ ][A-Z]{2}$/i";
        $pattern_chassis = "/^[0-9ABCDEFGHJKLMNPRSTUVWXYZ]{17}$/i";

        for($i = 0; $i < count($vehicles); $i++){
                array_push($filter_list, $vehicles[$i]);
        }
        for($i = 0; $i < count($filter_list); $i++){
            if(($filter_list[$i]->id_bee2link === NULL && $filter_list[$i]->id_client_bee2link === NULL) && ($filter_list[$i]->pvo_sent !== NULL)){
                array_push($trash, $filter_list[$i]);
            }
            elseif(($filter_list[$i]->id_pvo === NULL && $filter_list[$i]->id_client_pvo === NULL) && ($filter_list[$i]->bee2link_sent !== NULL)){
                array_push($trash, $filter_list[$i]);
            }

            else{
                array_push($list_vehicles, $filter_list[$i]);
            }
        }

        $users = DB::connection('mysql2')
        ->table('users')
        ->select('id', 'entreprise', 'name','email','tel1')
        ->orderBy('updated_at', 'desc')
        ->get();

        $array_sending_mail_operator = [];

        foreach($list_vehicles as $value){
            if(!in_array(["operator_id" => $value->operator_id, "email" => "", "tel" => "", "name" => "", "vehicules" => []], $array_sending_mail_operator))
            {
                if( !(preg_match($pattern_immat_1, $value->name) || preg_match($pattern_immat_2, $value->name) || preg_match($pattern_immat_3, $value->name) || preg_match($pattern_chassis, $value->name) ))
                 {
                    array_push($array_sending_mail_operator,[
                        "operator_id" => $value->operator_id,
                        "email" => "",
                        "tel" => "",
                        "name" => "",
                        "vehicules" => []
                    ]);
                 }
            }
        }
        for($i = 0; $i < count($array_sending_mail_operator); $i++){
            for($y = 0; $y < count($users); $y++){
                if($users[$y]->id === $array_sending_mail_operator[$i]["operator_id"]){
                    if(env('EMAIL_DEV_TEST_TO_ALL') == TRUE){
                        $array_sending_mail_operator[$i]["email"] = env('EMAIL');
                    }
                    else{
                        $array_sending_mail_operator[$i]["email"] = $users[$y]->email;
                    }
                    $array_sending_mail_operator[$i]["tel"] = $users[$y]->tel1;
                    $array_sending_mail_operator[$i]["name"] = $users[$y]->name;
                }
            }
        }
        for($i = 0; $i < count($list_vehicles); $i++){
            for($y = 0; $y < count($array_sending_mail_operator); $y++){
                if($list_vehicles[$i]->operator_id === $array_sending_mail_operator[$y]["operator_id"]){
                    // if(($list_vehicles[$i]->id_bee2link !== NULL || $list_vehicles[$i]->id_client_bee2link !== NULL) && $list_vehicles[$i]->bee2link_sent === NULL){
                        if(preg_match($pattern_immat_1, $list_vehicles[$i]->name) || preg_match($pattern_immat_2, $list_vehicles[$i]->name) || preg_match($pattern_immat_3, $list_vehicles[$i]->name) || preg_match($pattern_chassis, $list_vehicles[$i]->name)){
                            // array_push($array_sending_mail_operator[$y]["vehicules"], [
                            //     "id" => $list_vehicles[$i]->id,
                            //     "name" => $list_vehicles[$i]->name,
                            //     "error1" => "vehicule non remonté chez Bee2link",
                            //     "client_id" => $list_vehicles[$i]->client_id,
                            //     "manager_id" => $list_vehicles[$i]->manager_id,
                            //     "operator_id" => $list_vehicles[$i]->operator_id
                            // ]);
                        }
                        else{
                            array_push($array_sending_mail_operator[$y]["vehicules"], [
                                "id" => $list_vehicles[$i]->id,
                                "name" => $list_vehicles[$i]->name,
                                // "error1" => "vehicule non remonté chez Bee2link",
                                "error2" => "IMMAT ou VIN invalide",
                                "client_id" => $list_vehicles[$i]->client_id,
                                "manager_id" => $list_vehicles[$i]->manager_id,
                                "operator_id" => $list_vehicles[$i]->operator_id
                            ]);
                        }
                    // }
                    // elseif(($list_vehicles[$i]->id_pvo !== NULL || $list_vehicles[$i]->id_client_pvo !== NULL) && $list_vehicles[$i]->pvo_sent === NULL){
                    //     if(preg_match($pattern_immat_1, $list_vehicles[$i]->name) || preg_match($pattern_immat_2, $list_vehicles[$i]->name) || preg_match($pattern_immat_3, $list_vehicles[$i]->name) || preg_match($pattern_chassis, $list_vehicles[$i]->name)){
                    //         // array_push($array_sending_mail_operator[$y]["vehicules"], [
                    //         //     "id" => $list_vehicles[$i]->id,
                    //         //     "name" => $list_vehicles[$i]->name,
                    //         //     "error1" => "vehicule non remonté chez PVO",
                    //         //     "client_id" => $list_vehicles[$i]->client_id,
                    //         //     "manager_id" => $list_vehicles[$i]->manager_id,
                    //         //     "operator_id" => $list_vehicles[$i]->operator_id
                    //         // ]);
                    //     }
                    //     else{
                    //         array_push($array_sending_mail_operator[$y]["vehicules"], [
                    //             "id" => $list_vehicles[$i]->id,
                    //             "name" => $list_vehicles[$i]->name,
                    //             "error1" => "vehicule non remonté chez PVO",
                    //             "error2" => "IMMAT ou VIN invalide",
                    //             "client_id" => $list_vehicles[$i]->client_id,
                    //             "manager_id" => $list_vehicles[$i]->manager_id,
                    //             "operator_id" => $list_vehicles[$i]->operator_id
                    //         ]);
                    //     }
                    // }
                }
            }
        }
        if(env('EMAIL_DEV_TEST') == TRUE){
            for($i=0; $i < count($array_sending_mail_operator); $i++){
                if($i === count($array_sending_mail_operator) - 1)
                {
                    $array_sending_mail_operator[$i]['email'] = env('EMAIL');
                }
            }
        }
        return $array_sending_mail_operator;
    }

    static function listVehiclesImmatNotFound()
    {
        $manager_id = env('MANAGER_ID');
        $B2L = env('B2L');
        $PVO = env('PVO');

        date_default_timezone_set('Europe/Paris');
        $datetime = strtotime('-' . env('DATE') . ' days');
        $date_prise_en_compte = date('Y-m-d H:i:s', $datetime);
        $datetime1 = strtotime('-1 days');
        $newdate = date('Y-m-d H:i:s', $datetime1);

        $list = DB::connection('mysql2')
        ->table("vehicules")
        ->Join("users", "vehicules.client_id", "=", "users.id")
        ->select(
            "vehicules.id",
            "accepted",
            "vehicules.name",
            "manager_id",
            "client_id",
            "users.id_bee2link",
            "id_client_bee2link",
            "statut_bee2link",
            "bee2link_sent",
            "users.id_pvo",
            "id_client_pvo",
            "vehicules.pvo_sent",
            "operator_id",
            "mail_sent_operator",
            "vehicules.created_at",
            "vehicules.updated_at"
        )
        ->where(function($query){
            $query->where("accepted", "=", 1)
                  ->where("vehicules.deleted_at", "=", NULL);
        })
        ->where(function($query){
            $query->where("pvo_sent", "=", NULL)
                  ->orWhere("bee2link_sent", "=", NULL);
        })
        ->where(function($query){
            $query->where("users.id_pvo", "!=", NULL)
                  ->orWhere("users.id_bee2link", "!=", NULL)
                  ->orWhere("vehicules.id_client_pvo", "!=", NULL)
                  ->orWhere("vehicules.id_client_bee2link", "!=", NULL);
        })
        ->where(function($query){
            $query->where("mail_sent_operator", "<", 3)
                  ->orWhere("mail_sent_operator", "=", NULL);

        })
        ->where("vehicules.updated_at", ">=", $date_prise_en_compte)
        ->orderBy("vehicules.updated_at", "desc");

        if($manager_id !== NULL)
        {
            $vehicles = $list->where('manager_id', '=', $manager_id)->get();
        }
        else
        {
           $vehicles = $list->get();
        }

        $trash = [];
        $filter_list = [];
        $list_vehicles = [];

        $pattern_immat_1 = "/^[A-Z]{2}[0-9]{3}[A-Z]{2}$/i";
        $pattern_immat_2 = "/^[A-Z]{2}[-][0-9]{3}[-][A-Z]{2}$/i";
        $pattern_immat_3 = "/^[A-Z]{2}[ ][0-9]{3}[ ][A-Z]{2}$/i";
        $pattern_chassis = "/^[0-9ABCDEFGHJKLMNPRSTUVWXYZ]{17}$/i";

        for($i = 0; $i < count($vehicles); $i++){
                array_push($filter_list, $vehicles[$i]);
        }
        for($i = 0; $i < count($filter_list); $i++){
            if((($filter_list[$i]->id_bee2link === NULL && $filter_list[$i]->id_client_bee2link === NULL) && ($filter_list[$i]->pvo_sent !== NULL))){
                array_push($trash, $filter_list[$i]);
            }
            elseif(($filter_list[$i]->id_pvo === NULL && $filter_list[$i]->id_client_pvo === NULL) && ($filter_list[$i]->bee2link_sent !== NULL)){
                array_push($trash, $filter_list[$i]);
            }

            else{
                array_push($list_vehicles, $filter_list[$i]);
            }
        }

        $users = DB::connection('mysql2')
        ->table('users')
        ->select('id', 'entreprise', 'name','email','tel1')
        ->orderBy('updated_at', 'desc')
        ->get();

        $array_sending_mail_operator = [];

        foreach($list_vehicles as $value){
            if(!in_array(["operator_id" => $value->operator_id, "email" => "", "tel" => "", "name" => "", "vehicules" => []], $array_sending_mail_operator)){
                if(preg_match($pattern_immat_1, $value->name) || preg_match($pattern_immat_2, $value->name) || preg_match($pattern_immat_3, $value->name) || preg_match($pattern_chassis, $value->name)){
                    array_push($array_sending_mail_operator,[
                        "operator_id" => $value->operator_id,
                        "email" => "",
                        "tel" => "",
                        "name" => "",
                        "vehicules" => []
                    ]);
                }
            }
        }
        for($i = 0; $i < count($array_sending_mail_operator); $i++){
            for($y = 0; $y < count($users); $y++){
                if($users[$y]->id === $array_sending_mail_operator[$i]["operator_id"]){
                    if(env('EMAIL_DEV_TEST_TO_ALL') == TRUE)
                    {
                        $array_sending_mail_operator[$i]["email"] = env('EMAIL');
                    }
                    else
                    {
                        $array_sending_mail_operator[$i]["email"] = $users[$y]->email;
                    }
                    $array_sending_mail_operator[$i]["tel"] = $users[$y]->tel1;
                    $array_sending_mail_operator[$i]["name"] = $users[$y]->name;
                }
            }
        }
        for($i = 0; $i < count($list_vehicles); $i++){
            for($y = 0; $y < count($array_sending_mail_operator); $y++){
                if($list_vehicles[$i]->operator_id === $array_sending_mail_operator[$y]["operator_id"]){
                    if((($list_vehicles[$i]->id_bee2link !== NULL || $list_vehicles[$i]->id_client_bee2link !== NULL) && $list_vehicles[$i]->bee2link_sent === NULL) && (($list_vehicles[$i]->id_pvo !== NULL || $list_vehicles[$i]->id_client_pvo !== NULL) && $list_vehicles[$i]->pvo_sent === NULL)){
                        if(preg_match($pattern_immat_1, $list_vehicles[$i]->name) || preg_match($pattern_immat_2, $list_vehicles[$i]->name) || preg_match($pattern_immat_3, $list_vehicles[$i]->name) || preg_match($pattern_chassis, $list_vehicles[$i]->name)){
                            array_push($array_sending_mail_operator[$y]["vehicules"], [
                                "id" => $list_vehicles[$i]->id,
                                "name" => $list_vehicles[$i]->name,
                                "error1" => "vehicule non remonté chez Bee2link",
                                "error2" => "vehicule non remonté chez PVO",
                                "client_id" => $list_vehicles[$i]->client_id,
                                "manager_id" => $list_vehicles[$i]->manager_id,
                                "operator_id" => $list_vehicles[$i]->operator_id,
                                "mail_sent_operator" => $list_vehicles[$i]->mail_sent_operator,
                            ]);
                        }
                    }
                    elseif(($list_vehicles[$i]->id_pvo !== NULL || $list_vehicles[$i]->id_client_pvo !== NULL) && $list_vehicles[$i]->pvo_sent === NULL){
                        if(preg_match($pattern_immat_1, $list_vehicles[$i]->name) || preg_match($pattern_immat_2, $list_vehicles[$i]->name) || preg_match($pattern_immat_3, $list_vehicles[$i]->name) || preg_match($pattern_chassis, $list_vehicles[$i]->name)){
                            array_push($array_sending_mail_operator[$y]["vehicules"], [
                                "id" => $list_vehicles[$i]->id,
                                "name" => $list_vehicles[$i]->name,
                                "error1" => "vehicule non remonté chez PVO",
                                "client_id" => $list_vehicles[$i]->client_id,
                                "manager_id" => $list_vehicles[$i]->manager_id,
                                "operator_id" => $list_vehicles[$i]->operator_id,
                                "mail_sent_operator" => $list_vehicles[$i]->mail_sent_operator,
                            ]);
                        }
                    }
                    elseif(($list_vehicles[$i]->id_bee2link !== NULL || $list_vehicles[$i]->id_client_bee2link !== NULL) && $list_vehicles[$i]->bee2link_sent === NULL){
                        if(preg_match($pattern_immat_1, $list_vehicles[$i]->name) || preg_match($pattern_immat_2, $list_vehicles[$i]->name) || preg_match($pattern_immat_3, $list_vehicles[$i]->name) || preg_match($pattern_chassis, $list_vehicles[$i]->name)){
                            array_push($array_sending_mail_operator[$y]["vehicules"], [
                                "id" => $list_vehicles[$i]->id,
                                "name" => $list_vehicles[$i]->name,
                                "error1" => "vehicule non remonté chez Bee2link",
                                "client_id" => $list_vehicles[$i]->client_id,
                                "manager_id" => $list_vehicles[$i]->manager_id,
                                "operator_id" => $list_vehicles[$i]->operator_id,
                                "mail_sent_operator" => $list_vehicles[$i]->mail_sent_operator,
                            ]);
                        }
                    }
                }
            }
        }
        if(env('EMAIL_DEV_TEST') == TRUE){
            for($i=0; $i < count($array_sending_mail_operator); $i++){
                if($i === count($array_sending_mail_operator) - 1)
                {
                    $array_sending_mail_operator[$i]['email'] = env('EMAIL');
                }
            }
        }
        return $array_sending_mail_operator;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    static function edit($id)
    {
        date_default_timezone_set('Europe/Paris');
        $vehicules = DB::connection('mysql2')
                    ->table('vehicules')
                    ->join("users", "vehicules.operator_id", "=", "users.id")
                    ->select('vehicules.id', 'vehicules.name AS immat', 'client_id', 'operator_id', 'users.name AS operator_name', 'mail_sent_operator')
                    ->where('vehicules.id', '=', $id)
                    ->get();

        // dd($vehicules);
        switch ($vehicules[0]->mail_sent_operator) {
            case NULL:
                DB::connection('mysql2')
                    ->table('mail_sent_vehicles')
                    ->insert([
                    'id_vehicule' => $vehicules[0]->id,
                    'name' => $vehicules[0]->immat,
                    'client_id' => $vehicules[0]->client_id,
                    'operator_id' => $vehicules[0]->operator_id,
                    'operator_name' => $vehicules[0]->operator_name,
                    'mail_sent_operator' => 1,
                    'updated_at' => date('y-m-d H:i:s')
            ]);
                DB::connection('mysql2')
                    ->table('vehicules')
                    ->where('id', '=', $id)
                    ->update([
                    'mail_sent_operator' => 1,
                    'updated_at' => date('y-m-d H:i:s')
            ]);

                break;

            case 1:
                DB::connection('mysql2')
                ->table('mail_sent_vehicles')
                ->where('id_vehicule', '=', $id)
                ->update([
                    'mail_sent_operator' => 2,
                    'updated_at' => date('y-m-d H:i:s')
            ]);
                DB::connection('mysql2')
                ->table('vehicules')
                ->where('id', '=', $id)
                ->update([
                'mail_sent_operator' => 2,
                'updated_at' => date('y-m-d H:i:s')
            ]);
                break;

            case 2:
                DB::connection('mysql2')
                ->table('mail_sent_vehicles')
                ->where('id_vehicule', '=', $id)
                ->update([
                    'mail_sent_operator' => 3,
                    'updated_at' => date('y-m-d H:i:s')
            ]);
                DB::connection('mysql2')
                ->table('vehicules')
                ->where('id', '=', $id)
                ->update([
                'mail_sent_operator' => 3,
                'updated_at' => date('y-m-d H:i:s')
            ]);
                break;
        }
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
