<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;

class WHSQETableOfContentMeta extends BaseModel
{
    use HasFactory;

    protected $table = 'whsqe_table_of_content_meta';

    protected $fillable = [
        'whsq_report_id',
        'step_id',
        'parent_id',
        'child_id',
        'grandchild_id',
        'content',
        'image_path',
        'image_alt',
        'sort_order',
        'start_new',
        'customer_id',
        'workspace_id',
        'is_active'
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'sort_order' => 'integer',
        'start_new' => 'boolean'
    ];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

    /**
     * Get the WHSQ report this meta belongs to
     */
    public function whsqReport()
    {
        return $this->belongsTo(WhsqReport::class, 'whsq_report_id');
    }

    /**
     * Get the parent content
     */
    public function parentContent()
    {
        return $this->belongsTo(WHSQE_TableOfContent::class, 'parent_id');
    }

    /**
     * Get the child content
     */
    public function childContent()
    {
        return $this->belongsTo(WHSQE_TableOfContentChild::class, 'child_id');
    }

    /**
     * Get the grandchild content
     */
    public function grandchildContent()
    {
        return $this->belongsTo(WHSQE_TableOfContentGrandChild::class, 'grandchild_id');
    }

    /**
     * Get the options for this content
     */
    public function options()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id');
    }

    /**
     * Get the dates for this content
     */
    public function dates()
    {
        return $this->hasMany(WHSQEContentDate::class, 'content_meta_id');
    }

    /**
     * Get checkbox options
     */
    public function checkboxOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('option_type', 'checkbox');
    }

    /**
     * Get radio options
     */
    public function radioOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('option_type', 'radio');
    }

    /**
     * Get select options
     */
    public function selectOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('option_type', 'select');
    }

   

    /**
     * Get parent level options
     */
    public function parentOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('level', 'parent');
    }

    /**
     * Get child level options
     */
    public function childOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('level', 'child');
    }

    /**
     * Get grandchild level options
     */
    public function grandchildOptions()
    {
        return $this->hasMany(WHSQEContentOption::class, 'content_meta_id')
                    ->where('level', 'grandchild');
    }



  

    /**
     * Scope to filter by active status
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter by step
     */
    public function scopeByStep($query, $stepId)
    {
        return $query->where('step_id', $stepId);
    }

    /**
     * Scope to filter by report
     */
    public function scopeByReport($query, $reportId)
    {
        return $query->where('whsq_report_id', $reportId);
    }

    /**
     * Store image and return path
     */
    public static function storeImage($image, $path = 'whsq-report/images')
    {
        if (!$image) {
            return null;
        }

        // Generate filename with JPEG extension
        $filename = time() . '_' . uniqid() . '.jpg';
        
        // Get the temporary file path
        $tempPath = $image->getPathname();
        
        // Convert to JPEG and save
        $fullPath = $path . '/' . $filename;
        $storagePath = storage_path('app/public/' . $fullPath);
        
        // Ensure directory exists
        $directory = dirname($storagePath);
        if (!file_exists($directory)) {
            mkdir($directory, 0755, true);
        }
        
        // Convert and save as JPEG
        self::convertUploadedImageToJpeg($tempPath, $storagePath);
        
        return $fullPath;
    }

    /**
     * Convert uploaded image file to JPEG format and save
     */
    private static function convertUploadedImageToJpeg($sourcePath, $destinationPath)
    {
        try {
            // Get image info
            $imageInfo = getimagesize($sourcePath);
            
            if ($imageInfo === false) {
                throw new \Exception('Invalid image file');
            }
            
            $mimeType = $imageInfo['mime'];
            $width = $imageInfo[0];
            $height = $imageInfo[1];
            
            // Create image resource based on MIME type
            switch ($mimeType) {
                case 'image/jpeg':
                    $image = imagecreatefromjpeg($sourcePath);
                    break;
                case 'image/png':
                    $image = imagecreatefrompng($sourcePath);
                    break;
                case 'image/gif':
                    $image = imagecreatefromgif($sourcePath);
                    break;
                case 'image/webp':
                    $image = imagecreatefromwebp($sourcePath);
                    break;
                default:
                    throw new \Exception('Unsupported image format: ' . $mimeType);
            }
            
            if ($image === false) {
                throw new \Exception('Failed to create image resource');
            }
            
            // Create a white background for JPEG (since JPEG doesn't support transparency)
            $jpegImage = imagecreatetruecolor($width, $height);
            $white = imagecolorallocate($jpegImage, 255, 255, 255);
            imagefill($jpegImage, 0, 0, $white);
            
            // Copy the original image onto the white background
            imagecopy($jpegImage, $image, 0, 0, 0, 0, $width, $height);
            
            // Save as JPEG with high quality (90%)
            $success = imagejpeg($jpegImage, $destinationPath, 90);
            
            // Clean up memory
            imagedestroy($image);
            imagedestroy($jpegImage);
            
            if (!$success) {
                throw new \Exception('Failed to save JPEG image');
            }
            
        } catch (\Exception $e) {
            // Fallback: copy the original file if conversion fails
            copy($sourcePath, $destinationPath);
            
            // Log the error for debugging
            Log::warning('Uploaded image conversion to JPEG failed, saved original format', [
                'error' => $e->getMessage(),
                'source_path' => $sourcePath,
                'destination_path' => $destinationPath
            ]);
        }
    }

    /**
     * Process summernote content and extract/save images
     */
    public static function processSummernoteContent($content, $reportId, $stepId)
    {
        if (!$content) {
            return $content;
        }
        // Create directory if it doesn't exist
        $uploadPath = public_path('whsq-report/images');
        if (!file_exists($uploadPath)) {
            mkdir($uploadPath, 0755, true);
        }
        
        // Extract base64 images from summernote content while preserving all attributes
        $pattern = '/<img([^>]*?)src="data:image\/([^;]+);base64,([^"]+)"([^>]*?)>/i';
        $processedContent = preg_replace_callback($pattern, function($matches) use ($uploadPath, $reportId, $stepId) {
            $beforeSrc = $matches[1];
            $imageType = $matches[2];
            $base64Data = $matches[3];
            $afterSrc = $matches[4];
            
            // Generate unique filename with JPEG extension
            $filename = 'whsq_' . $reportId . '_' . $stepId . '_' . time() . '_' . uniqid() . '.jpg';
            $filePath = $uploadPath . '/' . $filename;
            
            // Convert and save the image as JPEG
            self::convertToJpeg($base64Data, $imageType, $filePath);
            
            // Preserve existing attributes and add default ones if missing
            $attributes = $beforeSrc . $afterSrc;
            
            // Add alt attribute if not present
            if (strpos($attributes, 'alt=') === false) {
                $attributes .= ' alt="WHSQ Report Image"';
            }
            
            // Add class if not present
            if (strpos($attributes, 'class=') === false) {
                $attributes .= ' class="img-fluid"';
            } else {
                // Add img-fluid to existing class if not already present
                if (strpos($attributes, 'img-fluid') === false) {
                    $attributes = preg_replace('/class="([^"]*)"/', 'class="$1 img-fluid"', $attributes);
                }
            }
            
            // Return the new image with preserved and enhanced attributes
            return '<img' . $attributes . ' src="/whsq-report/images/' . $filename . '">';
        }, $content);

        return $processedContent;
    }

    /**
     * Convert base64 image data to JPEG format and save
     */
    private static function convertToJpeg($base64Data, $originalType, $filePath)
    {
        try {
            // Decode the base64 data
            $imageData = base64_decode($base64Data);
            
            // Create image resource from the decoded data
            $image = imagecreatefromstring($imageData);
            
            if ($image === false) {
                throw new \Exception('Failed to create image from string');
            }
            
            // Create a white background for JPEG (since JPEG doesn't support transparency)
            $width = imagesx($image);
            $height = imagesy($image);
            $jpegImage = imagecreatetruecolor($width, $height);
            
            // Fill with white background
            $white = imagecolorallocate($jpegImage, 255, 255, 255);
            imagefill($jpegImage, 0, 0, $white);
            
            // Copy the original image onto the white background
            imagecopy($jpegImage, $image, 0, 0, 0, 0, $width, $height);
            
            // Save as JPEG with high quality (90%)
            $success = imagejpeg($jpegImage, $filePath, 90);
            
            // Clean up memory
            imagedestroy($image);
            imagedestroy($jpegImage);
            
            if (!$success) {
                throw new \Exception('Failed to save JPEG image');
            }
            
        } catch (\Exception $e) {
            // Fallback: save the original image data if conversion fails
            file_put_contents($filePath, base64_decode($base64Data));
            
            // Log the error for debugging
            Log::warning('Image conversion to JPEG failed, saved original format', [
                'error' => $e->getMessage(),
                'original_type' => $originalType,
                'file_path' => $filePath
            ]);
        }
    }

    /**
     * Get the full image URL
     */
    public function getImageUrlAttribute()
    {
        if ($this->image_path) {
            return asset('storage/' . $this->image_path);
        }
        return null;
    }

    /**
     * Get the public image URL (for images stored in public folder)
     */
    public function getPublicImageUrlAttribute()
    {
        if ($this->image_path && strpos($this->image_path, 'whsq-report/') === 0) {
            return asset($this->image_path);
        }
        return null;
    }

    /**
     * Process content to replace image paths with proper URLs
     */
    public function getProcessedContentAttribute()
    {
        if (!$this->content) {
            return null;
        }

        $content = $this->content;
        
        // Replace relative image paths with full URLs while preserving all img tag attributes
        $content = preg_replace_callback('/<img([^>]*?)src="([^"]+)"([^>]*?)>/i', function($matches) {
            $beforeSrc = $matches[1];
            $src = $matches[2];
            $afterSrc = $matches[3];
            
            // If it's a relative path to our whsq-report folder, make it absolute
            if (strpos($src, '/whsq-report/') === 0) {
                $newSrc = asset($src);
            } else {
                $newSrc = $src;
            }
            
            // Reconstruct the full img tag with all attributes preserved
            return '<img' . $beforeSrc . 'src="' . $newSrc . '"' . $afterSrc;
        }, $content);

        return $content;
    }

    /**
     * Delete image file
     */
    public function deleteImage()
    {
        if ($this->image_path && Storage::disk('public')->exists($this->image_path)) {
            Storage::disk('public')->delete($this->image_path);
        }
    }
} 