<?php
// app/Http/Controllers/EmailController.php

namespace App\Http\Controllers;

use App\Services\MailService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Mail\TripPlanEmail;
use Illuminate\Support\Facades\Mail;

class EmailController extends Controller
{
    public function sendHtmlEmail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'travel_agent_id' => 'required|exists:travel_agents,id',
            'to' => 'required|email',
            'subject' => 'required|string',
            'html_content' => 'required|string',
            'cc' => 'sometimes|array',
            'cc.*' => 'email',
            'bcc' => 'sometimes|array',
            'bcc.*' => 'email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        // Create a custom HTML view on the fly
        $viewContent = $request->html_content;

        $emailData = [
            'view' => 'emails.dynamic-html',
            'data' => [
                'content' => $request->html_content,
                'subject' => $request->subject,
                'travelAgentId' => $request->travel_agent_id
            ],
            'to' => $request->to,
            'subject' => $request->subject,
            'cc' => $request->cc,
            'bcc' => $request->bcc,
        ];

        $result = MailService::sendEmail($request->travel_agent_id, $emailData);

        if ($result['success']) {
            return response()->json([
                'success' => true,
                'message' => 'Email sent successfully'
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => $result['message']
            ], 500);
        }
    }

    public function sendTemplateEmail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'travel_agent_id' => 'required|exists:travel_agents,id',
            'to' => 'required|email',
            'subject' => 'required|string',
            'template' => 'required|string', // email template name
            'data' => 'required|array', // template data
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        $emailData = [
            'view' => 'emails.' . $request->template,
            'data' => $request->data,
            'to' => $request->to,
            'subject' => $request->subject,
            'cc' => $request->cc,
            'bcc' => $request->bcc,
        ];

        $result = MailService::sendEmail($request->travel_agent_id, $emailData);

        if ($result['success']) {
            return response()->json([
                'success' => true,
                'message' => 'Email sent successfully'
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => $result['message']
            ], 500);
        }
    }

    // Add this method to your EmailController.php
    // In EmailController.php - Replace the entire method
public function sendTripPlanEmail(Request $request)
{
    \Log::info('Trip Plan Email Request:', $request->all());

    try {
        $validator = Validator::make($request->all(), [
            'travel_agent_id' => 'required|exists:travel_agents,id',
            'to' => 'required|email',
            'subject' => 'required|string',
            'invoice' => 'required|array',
            'travel_agent' => 'required|array',
            'user' => 'required|array',
            'payments' => 'sometimes|array',
        ]);

        if ($validator->fails()) {
            \Log::error('Validation failed:', $validator->errors()->toArray());
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors()
            ], 422);
        }

        // Calculate additional data for the template
        $startDate = \Carbon\Carbon::parse($request->invoice['tour_start_day'])->format('M j, Y');
        $endDate = \Carbon\Carbon::parse($request->invoice['tour_start_day'])
            ->addDays(count($request->invoice['trip_days']) - 1)
            ->format('M j, Y');
        
        $paymentPercentage = $request->invoice['final_price'] > 0 
            ? ($request->invoice['total_paid_amount'] / $request->invoice['final_price']) * 100 
            : 0;

        $emailData = [
            'view' => 'emails.trip-plan-enhanced', // Changed from 'emails.trip-plan'
            'data' => [
                'invoice' => $request->invoice,
                'travelAgent' => $request->travel_agent,
                'user' => $request->user,
                'payments' => $request->payments ?? [],
                'startDate' => $startDate,
                'endDate' => $endDate,
                'paymentPercentage' => $paymentPercentage,
                'currentDate' => now()->format('F j, Y'),
            ],
            'to' => $request->to,
            'subject' => $request->subject,
            'cc' => $request->cc ?? [],
            'bcc' => $request->bcc ?? [],
        ];

        \Log::info('Sending email with data:', $emailData);

        $result = MailService::sendEmail($request->travel_agent_id, $emailData);

        if ($result['success']) {
            return response()->json([
                'success' => true,
                'message' => 'Trip plan email sent successfully'
            ]);
        } else {
            \Log::error('MailService error:', $result);
            return response()->json([
                'success' => false,
                'message' => $result['message']
            ], 500);
        }

    } catch (\Exception $e) {
        \Log::error('Trip plan email error:', [
            'message' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'trace' => $e->getTraceAsString()
        ]);
        
        return response()->json([
            'success' => false,
            'message' => 'Failed to send trip plan email: ' . $e->getMessage()
        ], 500);
    }
}
}