<?php

namespace App\Http\Controllers\Admin\Email;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\EmailConfigureRequest;
use App\Repositories\Admin\EmailTemplateRepository;
use App\Repositories\Interfaces\Admin\ConfigInterface;
use App\Repositories\SettingRepository;
use App\Traits\SendMailTrait;
use Brian2694\Toastr\Facades\Toastr;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class EmailController extends Controller
{
    use SendMailTrait;

    protected $configs;

    protected $emailTemplate;

    public function __construct(ConfigInterface $configs, EmailTemplateRepository $emailTemplate)
    {
        $this->configs = $configs;
        $this->emailTemplate = $emailTemplate;
    }

    public function serverConfiguration()
    {
        $mail_driver = setting('mail_driver');
        $data = [
            'mail_driver' => $mail_driver,
        ];

        return view('admin.email-setup.server-configuration', $data);
    }

    public function emailTemplate(): \Illuminate\Contracts\View\View|\Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\Contracts\Foundation\Application
    {
        try {
            $data = [
                'email_templates' => $this->emailTemplate->emailTemplate(),
            ];
            return view('admin.email-setup.email-template', $data);
        } catch (Exception $e) {
            Log::error(__('something_went_wrong_please_try_again'));

            return back();
        }
    }

    public function serverConfigurationUpdate(EmailConfigureRequest $request): \Illuminate\Http\RedirectResponse
    {

        $driver = $request->mail_server;
        if ($this->configs->update($request)) {

            if ($driver == 'smtp' || $driver == 'sendgrid' || $driver == 'mailgun' || $driver == 'sendinBlue' || $driver == 'zohoSMTP') {
                $mail_host = setting('smtp_server_address');
                $mail_username = setting('smtp_user_name');
                $mail_port = setting('smtp_mail_port');
                $mail_address = setting('mail_from_address');
                $name = setting('smtp_mail_from_name');
                $mail_password = setting('smtp_password');
                $mail_encryption_type = setting('smtp_encryption_type');
            } elseif ($request->mail_server == 'sendmail') {
                $sendmail_path = setting('sendmail_path');
            }

            if ($request->mail_server == 'sendmail') {
                envWrite('MAIL_MAILER', 'sendmail');
                envWrite('MAIL_HOST', '');
                envWrite('MAIL_PORT', '');
                envWrite('MAIL_USERNAME', '');
                envWrite('MAIL_PASSWORD', '');
                envWrite('MAIL_ENCRYPTION', '');
                envWrite('MAIL_FROM_ADDRESS', '');
                envWrite('MAIL_FROM_NAME', '');
                envWrite('SENDMAIL_PATH', $sendmail_path);
            } else {
                envWrite('MAIL_MAILER', 'smtp');
                envWrite('MAIL_HOST', $request->smtp_server_address);
                envWrite('MAIL_PORT', $request->smtp_mail_port);
                envWrite('MAIL_USERNAME', $request->smtp_user_name);
                envWrite('MAIL_PASSWORD', $request->smtp_password);
                envWrite('MAIL_ENCRYPTION', $request->smtp_encryption_type);
                envWrite('MAIL_FROM_ADDRESS', $request->mail_from_address);
                envWrite('MAIL_FROM_NAME', $request->smtp_mail_from_name);
            }

            Artisan::call('config:clear');
            Artisan::call('cache:clear');
            Artisan::call('view:clear');

            return redirect()->back()->with('toastr_success', __('updated_successfully'));
        } else {
            Log::error(__('something_went_wrong_please_try_again'));
            
            return redirect()->back()->with('toastr_error', __('something_went_wrong_please_try_again'));
        }
    }

    public function sendTestMail(Request $request)
    {
        $request->validate([
            'send_to' => 'required|email',
        ]);
        $send_to = $request->send_to;
        $template_data = $this->emailTemplate->testMail();
        $data = [
            'email_templates' => $template_data,
            'subject' => $template_data->subject,
        ];
        try {

            $this->sendmail($send_to, 'emails.test', $data);
            return redirect()->back()->with('toastr_success', __('successfully_email_send'));
        } catch (ValidationException $e) {
            return redirect()->back()->with('toastr_error', __('invalid_email_address_provided'));
        } catch (Exception $e) {
            Log::error('Error: ' . $e->getMessage(), [
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
            ]);
            return redirect()->back()->with('toastr_error', __('something_went_wrong_please_try_again'));
        }
    }

    public function templateBody(Request $request)
    {
        $templateBody = $this->emailTemplate->get($request->id);

        return response()->json($templateBody);
    }

    public function emailTemplateUpdate(Request $request): \Illuminate\Http\JsonResponse
    {
        $request->validate([
            'subject' => 'required',
            'body' => 'required',
        ]);
        try {
            $this->emailTemplate->update($request->all());
            $data = [
                'status' => 'success',
                'message' => __('update_successful'),
                'title' => __('success'),
                'is_reload' => true,
            ];
            return response()->json($data);
        } catch (Exception $e) {
            return response()->json([
                'error' => __('something_went_wrong_please_try_again'),
            ]);
            
        }
    }
}

