<?php

namespace App\Http\Controllers\Traits;

use App\Models\Adminsettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

trait AdminGeneralSettingTrait
{
    protected function storeSettings(Request $request)
    {
        $validator = $this->adminGeneralSettingValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        
        $validationData = $validator->validated();
        $workspace = auth()->user()->current_workspace_id;
        $createdBy = auth()->user()->id;
        
        // Process settings (both text and images)
        if (!empty($validationData['settings']) && is_array($validationData['settings'])) {
            foreach ($validationData['settings'] as $setting) {
                if (!isset($setting['key']) || !isset($setting['value'])) {
                    continue; // Skip invalid settings
                }
                
                $value = $setting['value'];
                
                // Check if value is an image (UploadedFile instance)
                if ($value instanceof \Illuminate\Http\UploadedFile) {
                    try {
                        $imagePath = $this->saveImageToPublicFolder($value, $setting['key']);
                        if ($imagePath) {
                            $value = $imagePath;
                        } else {
                            Log::error("Failed to save image for key: " . $setting['key']);
                            continue; // Skip this setting if image save failed
                        }
                    } catch (\Exception $e) {
                        Log::error("Error saving image for key {$setting['key']}: " . $e->getMessage());
                        continue; // Skip this setting if image save failed
                    }
                }
                
                Adminsettings::updateOrCreate(
                    [
                        'key' => $setting['key'],
                        'workspace' => $workspace,
                        'customer_id' => $createdBy,
                    ],
                    [
                        'value' => $value,
                    ]
                );
            }
        }
        
        return $this->message('Settings created successfully!');
    }

    protected function updateSettings(Request $request)
    {
        $validator = $this->adminGeneralSettingValidationRequest($request);
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }

        $validationData = $validator->validated();
        $workspace = auth()->user()->current_workspace_id;
        $createdBy = auth()->user()->id;
        $dateFormatChanged = false;
    
        if (!empty($validationData['settings']) && is_array($validationData['settings'])) {
            foreach ($validationData['settings'] as $setting) {
                if (!isset($setting['key']) || !isset($setting['value'])) {
                    continue; // Skip invalid settings
                }

                $value = $setting['value'];
    
                // STEP 4: Check if date format is being changed
                if ($setting['key'] === 'system_date_format') {
                    $existingSetting = Adminsettings::where('key', 'system_date_format')
                        ->where('workspace', $workspace)
                        ->where('customer_id', $createdBy)
                        ->first();
    
                    if (!$existingSetting || $existingSetting->value !== $value) {
                        $dateFormatChanged = true;
                    }
                }
    
                // Check if an existing setting already exists
                $existingSetting = Adminsettings::where('key', $setting['key'])
                    ->where('workspace', $workspace)
                    ->where('customer_id', $createdBy)
                    ->first();

                // Handle image uploads
                if ($value instanceof \Illuminate\Http\UploadedFile) {
                    try {
                        // Delete old image if it exists
                        
                        if ($existingSetting && $this->isImagePath($existingSetting->value)) {
                            // $this->deleteOldImage($existingSetting->value);
                        }

                        $imagePath = $this->saveImageToPublicFolder($value, $setting['key']);
                        if ($imagePath) {
                            $value = $imagePath;
                        } else {
                            Log::error("Failed to save image for key: " . $setting['key']);
                            continue; // Skip this setting if image save failed
                        }
                    } catch (\Exception $e) {
                        Log::error("Error saving image for key {$setting['key']}: " . $e->getMessage());
                        continue; // Skip this setting if image save failed
                    }
                }

                // Use updateOrCreate for clean logic
                Adminsettings::updateOrCreate(
                    [
                        'key' => $setting['key'],
                        'workspace' => $workspace,
                        'customer_id' => $createdBy,
                    ],
                    [
                        'value' => $value,
                    ]
                );
            }
        }
    
        // STEP 4: If date format changed, update session
        if ($dateFormatChanged) {
            $this->updateUserDateFormatSession($createdBy, $workspace);
        }
    
        return $this->message('Settings updated successfully!');
    }
    private function updateUserDateFormatSession($customerId, $workspaceId)
    {
        // Get new format from database
        $setting = Adminsettings::where('customer_id', $customerId)
            ->where('key', 'system_date_format')
            ->where('workspace', $workspaceId)
            ->first();
    
        $format = 'd-m-Y'; // Default
        
        if ($setting && $setting->value) {
            $formatMap = [
                'mm-dd-yyyy' => 'm-d-Y',
                'dd-mm-yyyy' => 'd-m-Y',
                'yyyy-mm-dd' => 'Y-m-d',
                'mm/dd/yyyy' => 'm/d/Y',
                'dd/mm/yyyy' => 'd/m/Y',
                'yyyy/mm/dd' => 'Y/m/d',
            ];
            $format = $formatMap[strtolower($setting->value)] ?? 'd-m-Y';
        }
    
        // Update session
        Session::put('user_date_format', $format);
    }
    protected function getSettings()
    {
        $workspace = auth()->user()->current_workspace_id;
        $settings = Adminsettings::where('workspace', $workspace)
            ->where('customer_id', auth()->user()->id)
            ->get();
        
        // // Mask password-related settings with asterisks
        // $passwordKeys = [
        //     'email_mail_password',
        // ];
        
        // $settings->transform(function ($setting) use ($passwordKeys) {
        //     // Check if the key contains password-related terms
        //     $isPasswordKey = false;
        //     foreach ($passwordKeys as $passwordKey) {
        //         if (stripos($setting->key, $passwordKey) !== false) {
        //             $isPasswordKey = true;
        //             break;
        //         }
        //     }
            
        //     // If it's a password key and has a value, mask it with asterisks
        //     if ($isPasswordKey && !empty($setting->value)) {
        //         $setting->value = str_repeat('*', strlen($setting->value));
        //     }
            
        //     return $setting;
        // });
        
        return $this->success($settings, 'Retrieved Settings successfully');
    }
    
    /**
     * Get unmasked email password after password verification (Super Admin only)
     */
    protected function getEmailPasswordSettings(Request $request)
    {
        // Validate request
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'password' => 'required|string',
        ]);
        
        if ($validator->fails()) {
            return $this->handleValidationFailure($validator);
        }
        
        $user = Auth::user();
        
        // Check if user is super admin (user_type == 1)
        if (!$user || $user->user_type != config('constants.user_types.admin')) {
            return $this->error('Unauthorized. Only super admin can access this endpoint.', 403);
        }
        
        // Verify the provided password matches the user's password
        if (!Hash::check($request->input('password'), $user->password)) {
            return $this->error('Invalid password. Access denied.', 401);
        }
        
        // Get the email_mail_password setting for super admin
        $workspace = $user->current_workspace_id;
        $emailPasswordSetting = Adminsettings::where('key', 'email_mail_password')
            ->where('workspace', $workspace)
            ->where('customer_id', $user->id)
            ->first();
        
        if (!$emailPasswordSetting) {
            return $this->error('Email password setting not found.', 404);
        }
        
        // Return the unmasked password value
        return $this->success([
            'key' => $emailPasswordSetting->key,
            'value' => $emailPasswordSetting->value,
            'id' => $emailPasswordSetting->id,
            'created_at' => $emailPasswordSetting->created_at,
            'updated_at' => $emailPasswordSetting->updated_at,
            'workspace' => $emailPasswordSetting->workspace,
        ], 'Email password retrieved successfully');
    }
    
    /**
     * Save image to public/AdminGeneralSettings folder
     */
    private function saveImageToPublicFolder($file, $key)
    {
        try {
            // Create directory if it doesn't exist
            $folderPath = public_path('AdminGeneralSettings');
            if (!file_exists($folderPath)) {
                mkdir($folderPath, 0755, true);
            }
            
            // Generate unique filename
            $extension = $file->getClientOriginalExtension();
            $filename = $key . '_' . time() . '_' . uniqid() . '.' . $extension;
            
            // Move file to public folder
            $file->move($folderPath, $filename);
            
            // Return relative path for database storage
            return 'AdminGeneralSettings/' . $filename;
            
        } catch (\Exception $e) {
            Log::error("Error saving image to public folder: " . $e->getMessage());
            return null;
        }
    }
    
    /**
     * Check if a value is an image path
     */
    private function isImagePath($value)
    {
        if (!is_string($value)) {
            return false;
        }
        
        // Check if it's our AdminGeneralSettings path
        if (strpos($value, 'AdminGeneralSettings/') !== false) {
            return true;
        }
        
        // Additional check for common image extensions
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp'];
        $extension = strtolower(pathinfo($value, PATHINFO_EXTENSION));
        
        return in_array($extension, $imageExtensions);
    }
    
    /**
     * Delete old image file
     */
    private function deleteOldImage($imagePath)
    {
        try {
            $fullPath = public_path($imagePath);
            if (file_exists($fullPath)) {
                unlink($fullPath);
                Log::info("Deleted old image: " . $imagePath);
            }
        } catch (\Exception $e) {
            Log::error("Error deleting old image {$imagePath}: " . $e->getMessage());
        }
    }
    
    /**
     * Get full URL for image paths
     */
    protected function getImageUrl($path)
    {
        if ($this->isImagePath($path)) {
            return asset($path);
        }
        return $path;
    }
}
