<?php

namespace App\Http\Controllers;

use App\Models\CompGallary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;

class CompGallaryController extends Controller
{
    /**
     * Get all CompGallary records.
     */
    public function index()
    {
        $galleries = CompGallary::with(['complaint', 'user'])->get();

        // Transform each gallery record
        $galleries->each(function ($gallery) {
            // Decode the JSON image paths and convert to full URLs
            if ($gallery->Image) {
                $imagePaths = json_decode($gallery->Image, true); // Decode as array
                $gallery->Image = array_map(function ($path) {
                    return url('/storage/' . $path); // Convert to full URL
                }, $imagePaths);
            }
        });

        return response()->json($galleries);
    }

    /**
     * Get a specific CompGallary record by Cg_Id.
     */
    public function show($id)
    {
        $gallery = CompGallary::with(['complaint', 'user'])->find($id);

        if (!$gallery) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Decode the JSON image paths and convert to full URLs
        if ($gallery->Image) {
            $imagePaths = json_decode($gallery->Image, true); // Decode as array
            $gallery->Image = array_map(function ($path) {
                return url('/storage/' . $path); // Convert to full URL
            }, $imagePaths);
        }

        return response()->json($gallery);
    }

    /**
     * Create a new CompGallary record with multiple image uploads.
     */
    /**
     * Create a new CompGallary record with multiple image uploads.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Cmp_Id'    => 'required|integer|exists:complaint_books,Cmp_Id',
            'Image'     => 'nullable|array', // Ensure multiple images
            'Image.*'   => 'image|mimes:jpeg,png,jpg,gif,svg', // Removed max:2048
            'Img_Date'  => 'nullable|string', // Accept string date format
            'U_Id'      => 'nullable|integer|exists:users_master,U_Id',
            'Img_Status' => 'nullable|string|max:1',
        ]);

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

        // Handle Img_Date
        $imgDate = null;
        if ($request->filled('Img_Date')) {
            try {
                $imgDate = Carbon::createFromFormat('d/m/Y H:i:s', $request->input('Img_Date'), 'Asia/Kolkata')
                    ->format('Y-m-d H:i:s'); // Convert to MySQL format
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid date format. Use dd/mm/yyyy H:i:s'], 422);
            }
        }

        // Define the base storage path
        $basePath = public_path('storage'); // Points to public/storage

        // Store images and generate relative paths
        $imagePaths = [];
        if ($request->hasFile('Image')) {
            foreach ($request->file('Image') as $image) {
                $originalName = $image->getClientOriginalName();
                $filePath = 'comp_gallary/' . $originalName;
                $destinationPath = $basePath . '/' . $filePath;

                // Check if file exists and rename with timestamp
                if (file_exists($destinationPath)) {
                    $filenameWithoutExt = pathinfo($originalName, PATHINFO_FILENAME);
                    $extension = $image->getClientOriginalExtension();
                    $newFileName = $filenameWithoutExt . '_' . time() . '.' . $extension;
                    $filePath = 'comp_gallary/' . $newFileName;
                    $destinationPath = $basePath . '/' . $filePath;
                }

                // Ensure the directory exists
                if (!file_exists(dirname($destinationPath))) {
                    mkdir(dirname($destinationPath), 0755, true);
                }

                // Move the image to the destination
                $image->move(dirname($destinationPath), basename($filePath));

                // Store relative path
                $imagePaths[] = $filePath;
            }
        }

        // Create record
        $gallery = CompGallary::create([
            'Cmp_Id'    => $request->input('Cmp_Id'),
            'Image'     => json_encode($imagePaths), // Store relative paths as JSON
            'Img_Date'  => $imgDate, // Use parsed date or null
            'U_Id'      => $request->input('U_Id'),
            'Img_Status' => $request->input('Img_Status'),
        ]);

        // Prepare response with full URLs
        $responseData = $gallery->toArray();
        $responseData['Image'] = array_map(function ($path) {
            return url('/storage/' . $path); // Convert relative paths to full URLs for response
        }, json_decode($gallery->Image, true) ?? []);

        return response()->json($responseData, 201);
    }

    /**
     * Update a CompGallary record by Cg_Id.
     */
    /**
     * Update a CompGallary record by Cg_Id.
     */
    public function update(Request $request, $id)
    {
        // Log request data for debugging (optional)
        Log::info('Update request data', [
            'all' => $request->all(),
            'files' => $request->file(),
            'hasFile_Image' => $request->hasFile('Image'),
        ]);

        $gallery = CompGallary::find($id);

        if (!$gallery) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Validation rules for Base64 strings
        $validator = Validator::make($request->all(), [
            'Cmp_Id'    => 'required|integer|exists:complaint_books,Cmp_Id',
            'Image'     => 'nullable|array', // Ensure multiple images
            'Image.*'   => 'nullable|string', // Validate each item as a Base64 string
            'Img_Date'  => 'nullable|string', // Accept string date format
            'U_Id'      => 'nullable|integer|exists:users_master,U_Id',
            'Img_Status' => 'nullable|string|max:1',
        ]);

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

        // Handle Img_Date
        $imgDate = null;
        if ($request->filled('Img_Date')) {
            $dateString = $request->input('Img_Date');
            try {
                $imgDate = Carbon::createFromFormat('d/m/Y H:i:s', $dateString, 'Asia/Kolkata')
                    ->format('Y-m-d H:i:s');
            } catch (\Exception $e) {
                return response()->json(['error' => 'Invalid date format. Please use dd/mm/yyyy H:i:s format.'], 422);
            }
        }

        // Define the base storage path
        $basePath = public_path('storage'); // Points to public/storage

        // Handle Base64 images for Image
        $imagePaths = [];
        if ($request->has('Image') && is_array($request->input('Image'))) {
            // Delete old images if they exist
            if (!empty($gallery->Image)) {
                $oldImages = json_decode($gallery->Image, true);
                if (is_array($oldImages)) {
                    foreach ($oldImages as $oldImagePath) {
                        $fullOldPath = public_path('storage/' . $oldImagePath);
                        if (file_exists($fullOldPath)) {
                            unlink($fullOldPath);
                            Log::info('Deleted old Image', ['path' => $oldImagePath]);
                        }
                    }
                }
            }

            // Process new Base64 images
            foreach ($request->input('Image') as $index => $base64Image) {
                // Remove data URI prefix if present (e.g., "data:image/jpeg;base64,")
                if (preg_match('/^data:image\/(jpeg|png|jpg|gif|svg);base64,/', $base64Image, $matches)) {
                    $extension = $matches[1] === 'svg' ? 'svg' : $matches[1]; // Use detected extension
                    $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
                } else {
                    $extension = 'jpg'; // Default to jpg if no prefix
                }

                // Decode Base64 string
                $imageData = base64_decode($base64Image);
                if ($imageData === false) {
                    return response()->json(['error' => "Invalid Base64 data for Image[{$index}]"], 422);
                }

                // Generate a unique filename
                $imageName = time() . '-' . uniqid() . '.' . $extension;
                $filePath = 'comp_gallary/' . $imageName;
                $destinationPath = $basePath . '/' . $filePath;

                // Ensure the directory exists
                if (!file_exists(dirname($destinationPath))) {
                    mkdir(dirname($destinationPath), 0755, true);
                }

                // Save the image
                file_put_contents($destinationPath, $imageData);
                $imagePaths[] = $filePath; // Store relative path
            }
        } else {
            // If no new images are provided, retain the existing images
            $imagePaths = json_decode($gallery->Image, true) ?? [];
        }

        // Update the record with new or existing images
        $gallery->update([
            'Cmp_Id'    => $request->input('Cmp_Id'),
            'Image'     => json_encode($imagePaths), // Store relative paths as JSON
            'Img_Date'  => $imgDate ?? $gallery->Img_Date, // Use existing Img_Date if null
            'U_Id'      => $request->input('U_Id'),
            'Img_Status' => $request->input('Img_Status'),
        ]);

        // Prepare response with full URLs
        $responseData = $gallery->toArray();
        $responseData['Image'] = array_map(function ($path) {
            return url('/storage/' . $path); // Convert relative paths to full URLs for response
        }, json_decode($gallery->Image, true));

        return response()->json($responseData);
    }

    /**
     * Delete a CompGallary record by Cg_Id.
     */
    public function destroy($id)
    {
        $gallery = CompGallary::find($id);

        if (!$gallery) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        // Delete images from storage
        $images = json_decode($gallery->Image, true);
        foreach ($images as $image) {
            $imagePath = str_replace(url('storage/'), '', $image);
            Storage::disk('public')->delete($imagePath);
        }

        $gallery->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
