<?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;
use Illuminate\Support\Facades\Storage;
use App\Models\Action;
use App\Models\Category;

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 href='".route('emails.copy.add', $row->id)."' class='btn btn-primary btn-sm'><i class='fa fa-edit'></i> Copy</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()
    {                
        $actionList = Action::orderBy('id', 'asc')->get();
        $categoryList = Category::pluck('name', 'id')->toArray();
        $body = '*user name*  *company name*  *designation*';
        return view('email/add',compact('body','actionList','categoryList'));
    }

    public function copy($id)
    {                
        $actionList = Action::orderBy('id', 'asc')->get();
        $categoryList = Category::pluck('name', 'id')->toArray();
        $body = '*user name*  *company name*  *designation*';
        $emails = EmailDraft::findorfail($id);
        return view('email/add',compact('body','actionList','categoryList','emails'));
    }

    /**
     * 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 {
            $emailData = $request->all();
           
            $emailData['email_type'] = ($request->radio_type == 'action') ? $request->email_action_type :  $request->email_category_type;
            $create = EmailDraft::create($emailData);

            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)
    {
        $actionList = Action::orderBy('id', 'asc')->get();
        $emails = EmailDraft::findorfail($id);
        $get_image = Attachment::where('email_id',$id)->get();
        $body = '*user name*  *company name*  *designation*';
        return view('email/edit', compact('emails','get_image','body','actionList'));
    }

    /**
     * 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($request->selection == 'action'){
                $email_type =  $request->email_type_action;
            }else{
                $email_type =  $request->email_type_category;
            }
        
            
            if(isset($email_type) && !empty($email_type))
            {
                $visitor = Visitor::findorfail($request->visitor_id);

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

                if($email_type == 'primary')
                {
                    if($teamMember->CustomerID == '1111111'){
                        $emailDraft = EmailDraft::find(auth()->user()->getUser()->primary_email);
                    }else{
                        $emailDraft = EmailDraft::find($teamMember->primary_email);
                    }    
                }
                else
                {
                    $emailDraft = EmailDraft::where('email_type',$email_type)->first();
                }

               

                $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->CustomerID == '1111111' ?  auth()->user()->getUser()->sender_email :  $teamMember->sender_email;
                $data['password'] = '';
                $data['from_name'] = $teamMember->CustomerID == '1111111' ?  auth()->user()->getUser()->sender_name :  $teamMember->sender_name;
                $data['receiver_email'] = $visitor->email;
                $data['subject'] = $emailDraft->subject;

                $emailContent = isset($emailDraft->content) ? $emailDraft->content : "";

                $userName =  $visitor->name; 
                $companyName = $visitor->company_name; 
                $designation =  $visitor->designation; 

                $emailContent = str_replace('*user name*', $userName, $emailContent);
                $emailContent = str_replace('*company name*', $companyName, $emailContent);
                $emailContent = str_replace('*designation*', $designation, $emailContent);
                
                $data['body'] = $emailContent.'<br>'.$teamMember->signature;

                //$data['body'] = $emailDraft->content;
                $data['customer_id'] = $teamMember->CustomerID == '1111111' ?  auth()->user()->getUser()->CustomerID : $visitor->customer_id;
                $data['cc_email'] = $teamMember->cc_email;
                
                if(!empty($data['from_email']) && !empty($data['receiver_email']))
                {
                    $result = $this->sendEmail($data);
                    // dd($result);
                    if($result  == 'true')
                    {
                        Alert::success('Success', 'Email send successfully');
                        // session(['successMsg' => '']);
                    }else{
                        Alert::error('Error',$result);
                    }
                }
            }
            else
            {
                Alert::error('Error', 'Please select email type');
                // session(['errorMsg' => '']);
            }
        }
        else {
            // session(['errorMsg' => 'Something went wrong!']);
            Alert::error('Error', $result);
        }
        return redirect()->back();
    }

    public function sendEmail($data)
    {
		//dd($data);
        $emailConfig = DB::table('email_config')->first();
        $customer_id = $data['customer_id'];
        $useremailconfig = DB::table('user_email_config')->where('fk_user_id','=',$customer_id)->first();


        $mail = new PHPMailer();

        $mail->IsSMTP(); // Set mailer to use SMTP
        
        if(isset($useremailconfig) && $useremailconfig != null){
            $emailConfig = $useremailconfig;

            $mail->Host = $emailConfig->host; // Specify main and backup server
            //$mail->Host = "Give IP Address"; // If the above does not work.
            $mail->Port = $emailConfig->port; // Set the SMTP port
            $mail->SMTPAuth = true; // Enable SMTP authentication
            $mail->Username = $emailConfig->username; // SMTP username
            $mail->Password = $emailConfig->password; // SMTP password
            $mail->SMTPSecure = $emailConfig->smtp_encryption; // Enable encryption, 'ssl' also accepted
        }else{
            $mail->Host = $emailConfig->host; // Specify main and backup server
            //$mail->Host = "Give IP Address"; // If the above does not work.
            $mail->Port = $emailConfig->smtp_port; // Set the SMTP port
            $mail->SMTPAuth = true; // Enable SMTP authentication
            $mail->Username = $emailConfig->username; // SMTP username
            $mail->Password = $emailConfig->password; // SMTP password
            $mail->SMTPSecure = $emailConfig->smtp_encryption; // Enable encryption, 'ssl' also accepted
        }

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

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

        if($data['cc_email'] != null && $data['cc_email'] != ""){
            $recipients = explode(',', $data['cc_email']);
            foreach($recipients as $ccemail)
            {
               $mail->AddCC($ccemail, $data['from_name']);
            }
        }
        $mail->IsHTML(true); // Set email format to HTML

        $sub = '=?UTF-8?B?'.base64_encode($data['subject']).'?=';
        $mail->Subject = $sub;
        $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();
    //    dd($mail->ErrorInfo);
        if($response)
        {
            return true;
        }
        else
        {
            \Illuminate\Support\Facades\log::info(['sendEmail' => $response]);
            return $mail->ErrorInfo;
        }
    }

    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;
                                    $data['customer_id'] = $visitor->customer_id;
                                    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']);
    }

    public function upload(Request $request)
    {
        $request->validate([
            'image' => 'required|image',
        ]);
        $file = $request->file('image');
        $destinationPath = public_path('uploads/email/draftsImages');
        if (!is_dir($destinationPath)) {
            mkdir($destinationPath, 0755, true);
        }
        $filename = time() . '-' . $file->getClientOriginalName();
        $file->move($destinationPath, $filename);
        $url = asset('uploads/email/draftsImages/' . $filename);
        return response()->json([
            'status' => 200,
            'url' => $url
        ]);
    }
    

}
