<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Http\Controllers\Traits\EmailTrait;
use App\Models\EmpCompanyDetails;
use App\Models\InductionDocument;
use Illuminate\Support\Facades\Log;

class SendInductionDocumentNotificationJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, EmailTrait;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 3;

    /**
     * The maximum number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 120;

    protected $employeeId;
    protected $documentId;
    protected $isUpdate;
    protected $isMajorUpdate;
    protected $customerId;

    /**
     * Create a new job instance.
     *
     * @param int $employeeId The employee ID
     * @param int $documentId The induction document ID
     * @param bool $isUpdate Whether this is an update (true) or new document (false)
     * @param bool $isMajorUpdate Whether this is a major update (only relevant if isUpdate is true)
     * @param int $customerId Customer ID for email details
     */
    public function __construct($employeeId, $documentId, $isUpdate = false, $isMajorUpdate = false, $customerId = null)
    {
        $this->employeeId = $employeeId;
        $this->documentId = $documentId;
        $this->isUpdate = $isUpdate;
        $this->isMajorUpdate = $isMajorUpdate;
        $this->customerId = $customerId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Log::info('SendInductionDocumentNotificationJob: Job execution started', [
            'employee_id' => $this->employeeId,
            'document_id' => $this->documentId,
            'customer_id' => $this->customerId,
            'is_update' => $this->isUpdate,
            'is_major_update' => $this->isMajorUpdate,
            'attempts' => $this->attempts() ?? 1
        ]);
        
        try {
            // Reload employee with relationships
            $employee = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)
                ->with('empPersonalDetails')
                ->find($this->employeeId);
            if (!$employee) {
                Log::warning("Employee not found for ID: {$this->employeeId}");
                return;
            }
            // Reload document
            $document = InductionDocument::find($this->documentId);
            if (!$document) {
                Log::warning("Document not found for ID: {$this->documentId}");
                return;
            }
            
            Log::info('SendInductionDocumentNotificationJob: Document and employee loaded', [
                'document_id' => $document->id,
                'document_customer_id' => $document->customer_id,
                'document_workspace_id' => $document->workspace_id,
                'job_customer_id' => $this->customerId,
                'employee_customer_id' => $employee->customer_id,
                'employee_workspace_id' => $employee->workspace_id
            ]);
            
            // Get employee email
            $employeeEmail = $employee->employee_email ?? null;
            if (!$employeeEmail || !filter_var($employeeEmail, FILTER_VALIDATE_EMAIL)) {
                Log::warning("Skipping email for employee ID {$this->employeeId}: Invalid or missing email");
                return;
            }
            // Get employee name
            $employeeName = 'there';
            if ($employee->empPersonalDetails) {
                $firstName = $employee->empPersonalDetails->first_name ?? '';
                $lastName = $employee->empPersonalDetails->last_name ?? '';
                $employeeName = trim($firstName . ' ' . $lastName) ?: 'there';
            }
            // Prepare email subject
            $subject = $this->isUpdate
                ? "Induction Document Updated - {$document->title}"
                : "New Induction Document - {$document->title}";
            $subject .= " | " . env('APP_NAME', 'WMS');
            
            // Use document's customer_id and workspace_id if job customer_id is null
            $finalCustomerId = $this->customerId ?? $document->customer_id;
            $finalWorkspaceId = $document->workspace_id;
            
            Log::info('SendInductionDocumentNotificationJob: Preparing email view', [
                'final_customer_id' => $finalCustomerId,
                'final_workspace_id' => $finalWorkspaceId,
                'employee_email' => $employeeEmail
            ]);
            
            // Prepare email content
            $emailContent = view('Emails.induction-document-notification', [
                'employee_name' => $employeeName,
                'document_title' => $document->title,
                'document_type' => $document->document_type ?? 'N/A',
                'document_version' => $document->version,
                'document_description' => $document->description ?? '',
                'is_update' => $this->isUpdate,
                'is_major_update' => $this->isMajorUpdate,
                'update_type' => $this->isUpdate ? ($this->isMajorUpdate ? 'Major' : 'Minor') : null,
                'subject' => $subject,
                'customer_id' => $finalCustomerId,
                'workspace_id' => $finalWorkspaceId,
            ])->render();
            
            Log::info('SendInductionDocumentNotificationJob: Email content rendered successfully', [
                'employee_email' => $employeeEmail,
                'subject' => $subject
            ]);
            
            // Prepare email with attachment
            $params = [
                'to' => $employeeEmail,
                'subject' => $subject,
                'msg' => $emailContent,
            ];
            
            Log::info('SendInductionDocumentNotificationJob: Calling SendInstantEmail', [
                'to' => $employeeEmail,
                'subject' => $subject
            ]);
            
            $emailResult = $this->SendInstantEmail($params);
            
            Log::info('SendInductionDocumentNotificationJob: SendInstantEmail completed', [
                'employee_email' => $employeeEmail,
                'result' => $emailResult ?? 'no_return_value'
            ]);
        } catch (\Exception $e) {
            Log::error("Failed to send induction document notification email: " . $e->getMessage(), [
                'employee_id' => $this->employeeId ?? 'unknown',
                'document_id' => $this->documentId ?? 'unknown',
                'trace' => $e->getTraceAsString(),
            ]);
            throw $e; // Re-throw to mark job as failed
        }
    }
}
