<?php

namespace App\Modules\Bookings\controllers\api\v1;

use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Comment;
use App\Seraph\Services\GlobalMailerService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class EmailCustomerControllerREST extends BaseController
{
    /**
     * Email customer from task detail page
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function emailCustomer(Request $request)
    {
        try {
            $taskId = $request->input('task_id');
            $sendTo = $request->input('send_to');
            $subject = $request->input('subject');
            $message = $request->input('message');

            if (!$taskId || !$sendTo || !$subject || !$message) {
                return response()->json(['error' => 'Missing required fields'], 400);
            }

            // Find the task
            $task = Task::find($taskId);

            if (!$task) {
                return response()->json(['error' => 'Task not found'], 404);
            }

            // Send email using global SMTP settings
            // Convert line breaks to <br> tags for HTML email
            $htmlMessage = nl2br($message);

            $sent = GlobalMailerService::send(
                'emails.customer-email',
                ['content' => $htmlMessage],
                function ($mail) use ($sendTo, $subject) {
                    $mail->to($sendTo)
                         ->subject($subject);
                },
                null, // from_email (use default from SMTP settings)
                null, // from_name (use default from SMTP settings)
                false  // use_cc_bcc = false to include CC/BCC from global SMTP settings
            );

            if (!$sent) {
                return response()->json(['error' => 'Failed to send email'], 500);
            }

            // Create a comment to log the email
            $user = Auth::user();
            $comment = new Comment();
            $comment->related_id = $taskId;
            $comment->related_type = 'task';
            $comment->message = $message;
            $comment->emailed_to = $sendTo;
            $comment->created_by = $user->id;
            $comment->public = true;
            $comment->save();

            // Log the email activity
            Log::info('Customer email sent', [
                'task_id' => $taskId,
                'sent_to' => $sendTo,
                'subject' => $subject,
                'user_id' => Auth::id()
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Email sent successfully',
                'comment' => $comment
            ]);

        } catch (\Exception $e) {
            Log::error('Failed to send customer email: ' . $e->getMessage(), [
                'task_id' => $request->input('task_id'),
                'exception' => $e
            ]);

            return response()->json([
                'error' => 'Failed to send email: ' . $e->getMessage()
            ], 500);
        }
    }
}
