<?php

namespace App\Http\Controllers;

use Alert;
use App\Models\EmailBatch;
use App\Models\EmailBatchLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\EmailDraft;
use App\Models\Attachment;
use App\Models\User;
use App\Models\Visitor;
use App\Classes\PHPMailer;
use DataTables;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class EmailController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = EmailDraft::get();
            return Datatables::of($data)
                    ->addIndexColumn()
                    ->addColumn('action', function($row){

                        $btn = "<a href='". route('emails.show',$row->id) ."' class='btn btn-primary btn-sm'><i class='fa fa-eye'></i> View</a>";
                        $btn .= " <a href='".route('emails.edit', $row->id)."' class='btn btn-primary btn-sm'><i class='fa fa-edit'></i> Edit</a>";
                        $btn .= ' <a id="'. $row->id .'" class="btn btn-danger btn-sm" onclick="confirmDelete(this)"><i class="fa fa-trash"></i> Delete</a>';

                        return $btn;
                    })
                    ->rawColumns(['content', 'action'])
                    ->make(true);
        }
        return view('email/index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('email/add');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $attachments = [];
        if ($files = $request->file('attachment')) {

            foreach ($files as $key => $file) {
                $name  = str_replace(' ', '_', $file->getClientOriginalName());
                $ext   = $file->getClientOriginalExtension();
                $attachment = md5(microtime() . $name) . "." . $ext;

                if($file->move(public_path(UPLOAD_EMAIL), $name))
                {
                    // $attachments[] = $attachment;
                    $attachments[] = $name;
                }
            }
        }

        try {
            $create = EmailDraft::create($request->all());

            if($create)
            {
                foreach ($attachments as $val) {
                    Attachment::insertGetId([
                        'email_id' => $create->id,
                        'attachment' => $val
                    ]);
                }

                Alert::success('Congrats', 'Email draft created successfully!');
                return redirect()->route('emails.index');
            }
        } catch (\Exception $e) {
            $error = $e->getMessage();
            \Log::error('error while creating Email Draft', ['data' => $request->all(), 'error' => $error]);
        }
        Alert::error('Sorry', 'Something went wrong! Please try again.');
        return redirect()->back()->withInput($request->all());
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $email = EmailDraft::findorfail($id);
        return view('email/view', compact('email'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $emails = EmailDraft::findorfail($id);
        $get_image = Attachment::where('email_id',$id)->get();
        return view('email/edit', compact('emails','get_image'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $attachments = [];
        if ($files = $request->file('attachment')) {

            foreach ($files as $key => $file) {
                $name  = str_replace(' ', '_', $file->getClientOriginalName());
                $ext   = $file->getClientOriginalExtension();
                $attachment = md5(microtime() . $name) . "." . $ext;

                // dd($file->move(public_path(UPLOAD_EMAIL), $attachment));
                if($file->move(public_path(UPLOAD_EMAIL), $name))
                {
                    // $attachments[] = $attachment;
                    $attachments[] = $name;
                }
            }
        }

        try {
            $email = EmailDraft::find($id);

            if($email)
            {
                $email->email_type = $request->email_type;
                $email->subject = $request->subject;
                $email->content = $request->content;
                if($email->save())
                {
                    foreach ($attachments as $val) {
                        Attachment::insertGetId([
                            'email_id' => $id,
                            'attachment' => $val
                        ]);
                    }

                    Alert::success('Congrats', 'Email draft updated successfully!');
                    return redirect()->route('emails.index');
                }
            }
            else
            {
                Alert::error('Sorry', 'Email Draft Not Found!');
            }
        } catch (\Exception $e) {
            $error = $e->getMessage();
            Alert::error('Sorry', 'Something went wrong! Please try again.');
            \Log::error('error while creating Email Draft', ['data' => $request->all(), 'error' => $error]);
        }
        return redirect()->back()->withInput($request->all());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $email = EmailDraft::find($id);

        if(!empty($email) && $email->delete())
        {
            Alert::success('Success', 'Email draft deleted successfully!');
            return response(['status' => true, 'message' => 'Email draft deleted successfully!']);
        }

        return response(['status' => false, 'message' => 'Something went wrong!']);
    }

    public function procsendEmail(Request $request)
    {
        if(isset($request->visitor_id) && !empty($request->visitor_id))
        {

            if(isset($request->email_type) && !empty($request->email_type))
            {
                $visitor = Visitor::findorfail($request->visitor_id);

                $teamMember = User::where('CustomerID', $visitor->customer_id)->first();

                if($request->email_type == 'primary')
                {
                    $emailDraft = EmailDraft::find($teamMember->primary_email);
                }
                else
                {
                    $emailDraft = EmailDraft::find($teamMember->follow_up_email);
                }

                $data = [];
                 if(isset($emailDraft->id)){
                     $data['attachments'] = DB::table('email_attachments')->where('email_id',$emailDraft->id)->get();
                 }else{
                     $data['attachments'] = null;
                 }
                $data['from_email'] = $teamMember->sender_email;
                $data['password'] = '';
                $data['from_name'] = $teamMember->sender_name;
                $data['receiver_email'] = $visitor->email;
                $data['subject'] = $emailDraft->subject;
                $data['body'] = $emailDraft->content;

                if(!empty($data['from_email']) && !empty($data['receiver_email']))
                {
                    $result = $this->sendEmail($data);
                    if($result)
                    {
                        session(['successMsg' => 'Email send successfully']);
                    }
                }
            }
            else
            {
                session(['errorMsg' => 'Please select email type']);
            }
        }
        else {
            session(['errorMsg' => 'Something went wrong!']);
        }
        return redirect()->back();
    }

    public function sendEmail($data)
    {
		//dd($data);
        $emailConfig = DB::table('email_config')->first();
        $mail = new PHPMailer();

        $mail->IsSMTP(); // Set mailer to use SMTP
        $mail->Host = $emailConfig->host; // Specify main and backup server
        //$mail->Host = "Give IP Address"; // If the above does not work.
        $mail->Port = 587; // Set the SMTP port
        $mail->SMTPAuth = true; // Enable SMTP authentication
        $mail->Username = $emailConfig->username; // SMTP username
        $mail->Password = $emailConfig->password; // SMTP password
        $mail->SMTPSecure = "tls"; // Enable encryption, 'ssl' also accepted

        $mail->From = $data['from_email'];
        $mail->FromName = $data['from_name'];

        $mail->AddAddress($data['receiver_email']); // Add a recipient

        $mail->IsHTML(true); // Set email format to HTML

        $mail->Subject = $data['subject'];
        $mail->Body = $data['body'];

         if(isset($data['attachments'])){
             // $url = "../../frenzincrm_api/public/uploads/email/attachments/";
             //$url = "../../frenzincrm/public/uploads/email/attachments/";
             $url = public_path(UPLOAD_EMAIL);

             foreach ($data['attachments'] as $key => $attach) {
                 $attachmentPath = $url . $attach->attachment;
                 $mail->addAttachment($attachmentPath);

             }
         }
        $response = $mail->Send();
        if($response)
        {
            return true;
        }
        else
        {
            \Illuminate\Support\Facades\log::info(['sendEmail' => $response]);
            return false;
        }
    }

    public function scheduleBatchMailCron()
    {
        DB::enableQueryLog();
        $pendingMailBatches = EmailBatch::whereStatus('pending')
            ->whereDate('schedule_date', '<=', Carbon::now())
            ->get();
        $mailConfigData = DB::table('email_config')->first();
        if(empty($mailConfigData)){
            return response()->json([
                'status' => false,
                'message' => 'Mail could not be sent because config data not found!'
            ]);
        }
        if(!empty($pendingMailBatches)){
            foreach($pendingMailBatches as $batchData)
            {
                $pendingBatchEmails = EmailBatchLog::where('batch_id',$batchData->id)
                    ->where('id','>', $batchData->last_id_sent)
                    ->where('status', 'pending')->get()->take((int)$batchData->hour_interval_mails);
                if($pendingBatchEmails->count() != 0) {
                    foreach ($pendingBatchEmails as $emailBatchLog)
                    {
                        $visitor = Visitor::findorfail($emailBatchLog->visitor_id);
                        if(!empty($visitor)){
                            $teamMember = User::where('CustomerID', $visitor->customer_id)->first();
                            if(!empty($teamMember)){
                                switch ($batchData->email_type){
                                    case 'primary' :
                                        $emailDraft = EmailDraft::find($teamMember->primary_email);
                                        break;
                                    case 'followup' :
                                        $emailDraft = EmailDraft::find($teamMember->follow_up_email);
                                        break;
                                    case 'other' :
                                        $emailDraft = EmailDraft::find($batchData->email_draft_id);
                                        break;
                                }
                                if(!empty($emailDraft))
                                {
                                    $data = [];
                                    $data['from_email'] = $teamMember->sender_email;
                                    $data['password'] = '';
                                    $data['from_name'] = $teamMember->sender_name;
                                    $data['receiver_email'] = $visitor->email;
                                    $data['subject'] = $emailDraft->subject;
                                    $data['body'] = $emailDraft->content;

                                    if(!empty($data['from_email']) && !empty($data['receiver_email']))
                                    {
                                        $result = $this->sendEmail($data);
                                        if($result)
                                        {
                                            $emailBatchLog->update(['status'=>'sent']);
                                            session(['successMsg' => 'Email send successfully']);
                                        }else{
                                            $emailBatchLog->update(['status'=>'fail']);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if($pendingBatchEmails->count() != 0) {
                    $batchData->update(['last_id_sent'=>$pendingBatchEmails->last()->id]);
                }else{
                    $batchData->update(['status'=>'sent']);
                }
            }
            return response()->json([
                'status' => true,
                'message' => 'Mail sent successfully!'
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => 'No Batch found!'
            ]);
        }
    }
    public function delete($id)
    {
        $email = Attachment::find($id);
        if (!empty($email) && $email->delete()) {

            return response()->json(['status' => true, 'message' => 'Email draft deleted successfully']);
        }

        return response()->json(['status' => false, 'message' => 'Something went wrong']);
    }

}
