<?php

namespace App\Http\Controllers;

use App\Mail\CarenceDocs;
use App\Mail\ReplyToEmail;
use App\Mail\SendAccordMail;
use App\Mail\SendFactureMail;
use App\Mail\SendMail;
use App\Models\Company;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Email;
use App\Models\Step;
use App\Models\Transaction;
use App\Models\TypeDocument;
use App\Models\User;
use Carbon\Carbon;
use DateTime;
use Illuminate\Http\Request;
use Illuminate\Mail\Mailables\Attachment;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use stdClass;
use Type;
use Webklex\PHPIMAP\Client;
use Webklex\PHPIMAP\Message;

class EmailController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */


    public function index()
    {
        $this->authorize('viewAny', Email::class);

        $emails = Email::with('step')->get();
        return view('email.index', compact('emails'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $this->authorize('create', Email::class);
        $types = TypeDocument::all();
        $steps = Step::all();
        return view('email.create', compact('steps', 'types'));
    }


    public function inbox(Request $request)
    {
        /** @var \Webklex\PHPIMAP\Client $client */

        $this->authorize('inbox', Email::class);


        $user = User::whereId(Auth::user()->id)->with('company')->withCount('company')->first();

        if($user->company_count>0){
        if ($request->company_id) {
            $company = Company::whereId($request->company_id)->first();
        }else{
            $company = Company::whereId($user->company[0]->id)->first();
        }
        if ($company->email_pro == null || $company->password == null) {
            return redirect()->route('home')->with('error', 'Demander A admin de Ajouter Email et Mot de Passe a cette Compagnie');
        }
        config(['imap.accounts.admin.username' => $company->email_pro]);
        config(['imap.accounts.admin.password' => $company->password_pro]);
        config(['imap.options.fetch_order' => 'desc']);

        $client = \Webklex\IMAP\Facades\Client::account('admin');
        //Connect to the IMAP Server
        $client->connect();

        //Get all Mailboxes
        /** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */

        $folders = $client->getFolders();

        if ($request->search) {

            foreach ($folders as $folder) {
                //Get all Messages of the current Mailbox $folder
                /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
                $ss = $folder->messages()->subject($request->search)->get();
                $messages = $ss->paginate(10);
            }
        } else {
            //Loop through every Mailbox
            /** @var \Webklex\PHPIMAP\Folder $folder */
            foreach ($folders as $folder) {
                //Get all Messages of the current Mailbox $folder
                /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
                $messages = $folder->messages()->all()->get();
                // $messages = $ss->paginate(10);
            }
        }

        }
        else{
            return redirect()->route('home')->with('error', 'Demander A admin de vous Affecter une Compagnie');

        }





        return view('email.inbox', compact('messages', 'user','company'));
    }


    public function compose($id)
    {
        $this->authorize('send', Email::class);

        $dossier = Dossier::whereId($id)->with('company')->first();
        $user = User::whereId(Auth::user()->id)->with('typedocument')->firstOrFail();
        $array = [];
        foreach ($user->typedocument as $type) {
            array_push($array, $type->id);
        }
        $imgs = Document::where('dossier_id', $dossier->id)->whereIn('type_document_id', $array)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 0);
        })->get();

        $pdfs = Document::where('dossier_id', $dossier->id)->whereIn('type_document_id', $array)->whereHas('typedocument', function ($query) {
            $query->where('is_pdf', 1);
        })->get();


        return view('email.compose', compact('imgs', 'pdfs', 'dossier'))->with('success', 'Email Envoyer Avec Succés');
    }

    public function search(Request $request)
    {
        // $this->authorize('inbox', Email::class);
        // if (!$request->search) {
        //     return redirect()->route('Email.inbox');
        // }
        // if (!$request->company_id) {
        //     return redirect()->route('Email.inbox');
        // }
        // /** @var \Webklex\PHPIMAP\Client $client */


        // config(['imap.accounts.admin.username' => $user->email_pro]);
        // config(['imap.accounts.admin.password' => $user->password_pro]);
        // $client = \Webklex\IMAP\Facades\Client::account('admin');
        // //Connect to the IMAP Server
        // $client->connect();
        // //Get all Mailboxes
        // /** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
        // $folders = $client->getFolders();
        // //Loop through every Mailbox
        // /** @var \Webklex\PHPIMAP\Folder $folder */
        // foreach ($folders as $folder) {
        //     //Get all Messages of the current Mailbox $folder
        //     /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
        //     $ss = $folder->messages()->subject($request->search)->get();
        //     $messages = $ss->paginate(10);
        // }


        // return view('email.inbox', compact('messages', 'user', 'companies'));
    }

    public function envoyer(Request $request)
    {
        $this->authorize('send', Email::class);

        $request->validate([
            'from' => 'required',
            'to' => 'required|email',
            'subject' => 'required',
            'content' => 'required'
        ]);
        $to = $request->to;
        $subject = $request->subject;
        $content = $request->content;
        $company  = Company::whereId($request->from)->firstOrFail();
        Mail::send('email.send', ['subject'=>$subject,'content' => $content], function ($message) use ($company,$subject,$to) {
            $message->from($company->email_pro, 'AMEA');
            $message->to($to);
            $message->subject($subject);
        });
        Transaction::create([
            'from' => $company->email_pro,
            'to' => $to,
            'subject' => $subject,
            'body' => $content,
            'user_id'=>Auth::user()->id
        ]);
        //  Mail::to($to)->from($from, 'Laravel')->send(new SendFactureMail($subject, $content,$from));

        return redirect()->back()->with('success', 'Mail est envoyer avec Succés');

    }

    public function send(Request $request)
    {
        $this->authorize('send', Email::class);

        $request->validate([
            'from' => 'required|email',
            'to' => 'required|email',
            'subject' => 'required',
            'content' => 'required'
        ]);
        $to = $request->to;
        $from = $request->from;
        $subject = $request->subject;
        $content = $request->content;
        $dossier = Dossier::whereId($request->dossier_id)->with('company')->firstOrFail();
        $from = $dossier->company->email_pro;
        $array = explode(",", $request->attachements);
        $documents = Document::whereIn('id', $array)->get();
        $from = $dossier->company->email_pro;

        Mail::send('email.send', ['subject'=>$subject,'content' => $content,'documents'=>$documents], function ($message) use ($from,$documents,$subject,$to) {
            $message->from($from, 'AMEA');
            $message->to($to);
            $message->subject($subject);
            foreach ($documents as $doc) {
                $file = Attachment::fromStorageDisk('s3', $doc->path);
                $message->attach($file);

            }
        });
        // Mail::to($to)->send(new SendAccordMail($documents, $content, $subject))
        $transaction = Transaction::create([
            'from' => $from,
            'to' => $to,
            'subject' => $subject,
            'body' => $content,
            'dossier_id' => $dossier->id,
            'user_id'=>Auth::user()->id
        ]);

        $transaction->document()->attach($documents);

        return redirect()->route('Dossier.show', $dossier->id)->with('success', 'Mail est envoyer avec Succés');
    }

    public function showinbox($id,$company)
    {

        $company = Company::whereId($company)->first();
        if ($company->email_pro == null || $company->password == null) {
            return redirect()->route('home')->with('error', 'Demander A admin de Ajouter Votre Email et Mot de Passe');
        }

        config(['imap.accounts.admin.username' => $company->email_pro]);
        config(['imap.accounts.admin.password' => $company->password]);
        /** @var \Webklex\PHPIMAP\Client $client */
        $client = \Webklex\IMAP\Facades\Client::account('admin');

        // Connect to the IMAP Server
        $client->connect();

        //Get all Mailboxes
        /** @var \Webklex\PHPIMAP\Support\FolderCollection $folders */
        $folders = $client->getFolders();

        //Loop through every Mailbox
        /** @var \Webklex\PHPIMAP\Folder $folder */
        foreach ($folders as $folder) {
            //Get all Messages of the current Mailbox $folder
            /** @var \Webklex\PHPIMAP\Support\MessageCollection $messages */
            $message = $folder->messages()->getMessage($uid = $id);
            $attachments = $message->getAttachments();
        }
        $attachments->each(function ($oAttachment) {
            $oAttachment->save(public_path('attachments/'));
        });
        // $replyMessage = 'reply test';
        // Mail::to($message->from[0]->mail)->send(new ReplyToEmail($replyMessage));

        return view('email.show', compact('message', 'attachments'));

    }
    public function show($id)
    {
        $this->authorize('create', Email::class);
        $email = Email::whereId($id)->with('step', 'typedocument')->first();
        $types = TypeDocument::all();
        return view('email.attach', compact('email', 'types'));
    }

    public function attach(Request $request, $id)
    {

        $this->authorize('create', Email::class);
        $email = Email::whereId($id)->with('step', 'typedocument')->first();
        if ($request->has('type')) {
            $email->typedocument()->detach();
            foreach ($request->type as $c) {
                $type = TypeDocument::findOrFail($c);
                $email->typedocument()->syncWithoutDetaching($type);
            }
        }
        return redirect()->back()->with('success', 'Succés');
    }

    public function store(Request $request)
    {
        $this->authorize('create', Email::class);

        $request->validate([
            'step_id' => 'required|unique:emails,step_id',
            'subject' => 'required',
            'content' => 'nullable',
            'delai' => 'numeric|required'
        ]);

        $email = Email::create([
            'step_id' => $request->step_id,
            'content' => $request->content,
            'delai' => $request->delai,
            'subject' => $request->subject,

        ]);

        if ($request->has('type')) {
            $email->typedocument()->detach();
            foreach ($request->type as $p) {
                $type = TypeDocument::findOrFail($p);
                $email->typedocument()->syncWithoutDetaching($type);
            }
        }

        return redirect()->route('Email.index')->with('success', 'Succés');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Email  $email
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $this->authorize('update', Email::class);

        $email = Email::whereId($id)->with('step', 'typedocument')->first();
        $steps = Step::where('id', '!=', $email->step_id)->get();
        return view('email.edit', compact('email', 'steps'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Email  $email
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->authorize('update', Email::class);

        $request->validate([
            'step_id' => 'required|unique:emails,step_id,' . $id,
            'subject' => 'required',
            'content' => 'nullable',
            'delai' => 'numeric|required'
        ]);
        $email = Email::whereId($id)->first();
        $email->subject = $request->subject;
        $email->content = $request->content;
        $email->delai = $request->delai;
        $email->step_id = $request->step_id;
        $email->update();
        // if ($request->has('type')) {
        //     foreach ($request->type as $p) {
        //         $type = TypeDocument::findOrFail($p);
        //         $email->typedocument()->attach($type->id);
        //     }
        // }

        return redirect()->route('Email.index')->with('success', 'Succés');

    }


    public function historique($id)
    {
        $transactions = Transaction::where('dossier_id',$id)->with('document.typedocument','user')->latest()->paginate(10);
        return view('email.historique', compact('transactions'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Email  $email
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $this->authorize('delete', Email::class);
        $email = Email::whereId($id)->first();
        $email->delete();
        return redirect()->route('Email.index')->with('success', 'Succés');
    }
}
