<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use App\Models\EmailTemplate;
use App\Traits\ResponseTrait;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class EmailTemplateController extends Controller
{
    use ResponseTrait;

    public function emailTemplate(Request $request)
    {
        if ($request->ajax()) {
            $temp = EmailTemplate::where('tenant_id', getTenantId());
            return datatables($temp)
                ->addIndexColumn()
                ->addColumn('body', function ($data) {
                    return $data->body;
                })
                ->addColumn('action', function ($data) {
                    return '<ul class="d-flex align-items-center cg-5 justify-content-center">
                    <li class="d-flex gap-2">
                        <button onclick="getEditModal(\'' . route('admin.setting.email-edit', $data->id) . '\'' . ', \'#edit-modal\')" class="d-flex justify-content-center align-items-center w-30 h-30 rounded-circle bd-one bd-c-ededed bg-white" data-bs-toggle="modal" data-bs-target="#alumniPhoneNo">
                            <img src="' . asset('assets/images/icon/edit.svg') . '" alt="edit" />
                        </button>
                    </li>
                </ul>';
                })
                ->rawColumns(['action','body'])
                ->make(true);
        }
        $data['title'] = __('Email Template');
        $data['showManageApplicationSetting'] = 'show';
        $data['activeEmailSetting'] = 'active-color-one';
        return view('admin.setting.email_temp.email-temp', $data);
    }

    public function emailTemplateSync()
    {
        $emailTemplates = [
            [
                'category' => 'Email Verification',
                'slug' => 'email-verification',
                'subject' => 'Verify Your Account',
                'body' => "Hello, {{username}}\nThank you for creating an account with us. We're excited to have you as a part of our community! Before you can start using your account, we need to verify your email address. Please click on the link below to complete the verification process:\nYour Otp is: {{otp}}",
            ],
            [
                'category' => 'Password Reset',
                'slug' => 'password-reset',
                'subject' => 'Reset your password',
                'body' => "We're sending you this email because you requested a password reset. Please use the OTP code below to create a new password:\nOTP Code: {{otp}}\nIf you didn't request a password reset, you can safely ignore this email. Your password will not be changed.\nThank you!",
            ],
            [
                'category' => 'Account Approval',
                'slug' => 'account-approval',
                'subject' => 'Your Account Approved',
                'body' => "We are pleased to inform you that your account application has been approved and your account is now active.\nThank you!",
            ],
            [
                'category' => 'Account Reject',
                'slug' => 'account-rejection',
                'subject' => 'Your Account Rejected',
                'body' => "We are pleased to inform you that your account application has been rejected and your account is now inactive. Please contact with admin\nThank you!",
            ],
            [
                'category' => 'Ticket Reservation',
                'slug' => 'ticket-confirmation',
                'subject' => 'Ticket Reservation',
                'body' => "Hi {{username}},\nThank you for reserving your tickets with us. Your booking has been confirmed with the following details:\nTicket No: {{ticket_number}}\nPlease keep this confirmation email for your records.\nIf you have any questions or need assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nWe look forward to welcoming you to the event!\nRegards,\n{{app_name}}\nClick here to more view your Ticket Reservation details.\n{{link}}",
            ],
            [
                'category' => 'Membership Apply Application',
                'slug' => 'membership-apply-application',
                'subject' => 'Membership Apply Application',
                'body' => "Hi {{username}},\nThank you for applying for membership with us.\nWe have received your membership application and will review it shortly. We will notify you once your application has been processed.\nIf you have any questions or need further assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nRegards,\n{{app_name}}\nClick here to more view your Membership Apply Application details.\n{{link}}",
            ],
            [
                'category' => 'Event Purchase',
                'slug' => 'event-purchase',
                'subject' => 'Event Purchase',
                'body' => "Hi {{username}},\nThank you for your purchase. Your order with the following details has been confirmed:\nOrder No: {{transaction_no}}\nIf you have any questions or need assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nWe look forward to seeing you at the event!\nRegards,\n{{app_name}}\nClick here to more view your Event Purchase details.\n{{link}}",
            ],
            [
                'category' => 'Payment Success',
                'slug' => 'payment-success',
                'subject' => 'Payment Successful',
                'body' => "Hi {{username}},\nWe are writing to inform you that your payment has been successfully processed for the following order:\nOrder No: {{transaction_no}}\nIf you have any questions or need assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nThank you for your payment. We appreciate your business and look forward to serving you again in the future.\nRegards,\n{{app_name}}",
            ],
            [
                'category' => 'Payment Cancel',
                'slug' => 'payment-cancel',
                'subject' => 'Payment Cancel',
                'body' => "Hi {{username}},\nWe are writing to inform you that your payment has been canceled for the following order:\nOrder No: {{transaction_no}}\nIf you have any questions or need assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nThank you for your payment. We appreciate your business and look forward to serving you again in the future.\nRegards,\n{{app_name}}",
            ],
            [
                'category' => 'Membership Approval',
                'slug' => 'membership-approval',
                'subject' => 'Membership Application Approved',
                'body' => "Hi {{username}},\nWe are pleased to inform you that your membership application with us has been approved!\nYou are now an official member of our community. We look forward to your active participation.\nIf you have any questions or need assistance, please feel free to contact us at:\nPhone: {{app_contact_number}}\nEmail: {{app_email}}\nWelcome aboard!\nRegards,\n{{app_name}}\nClick here to more view your Membership Approval details.\n{{link}}",
            ],
        ];

        $tenantId = getTenantId();

        foreach ($emailTemplates as $template) {
            EmailTemplate::firstOrCreate(
                ['tenant_id' => $tenantId, 'slug' => $template['slug']],
                array_merge($template, ['tenant_id' => $tenantId, 'default' => 1, 'status' => 1])
            );
        }

        return back()->with(['success' => __('Updated Successfully')]);
    }


    public function emailTempEdit($id)
    {

        $data['template'] = EmailTemplate::findOrFail($id);
        return view('admin.setting.email_temp.edit-form', $data);
    }

    public function emailTempUpdate(Request $request, $id){
        try {
            DB::beginTransaction();
            $tempObj = EmailTemplate::findOrFail($id);
            $tempObj->subject = $request->subject;
            $tempObj->body = $request->body;
            $tempObj->save();
            DB::commit();
            $message = getMessage(UPDATED_SUCCESSFULLY);
            return $this->success([], $message);
        } catch (Exception $e) {
            DB::rollBack();
            $message = getErrorMessage($e, $e->getMessage());
            return $this->error([], $message);
        }
    }
}
