<?php

namespace App\Http\Controllers;

use App\Models\ClassiGallary;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class ClassiGallaryController extends Controller
{
    /**
     * Get all ClassiGallary records.
     */
    public function index()
    {
        $galleries = ClassiGallary::with(['freeLClasssified', '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 ClassiGallary record by Clg_Id.
     */
    public function show($id)
    {
        $gallery = ClassiGallary::with(['freeLClasssified', '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 ClassiGallary record with multiple image uploads.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'FLC_Id' => 'required|integer|exists:free_l_classsified,FLC_Id',
            'Image' => 'nullable|array',
            'Image.*' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg',
            'Img_Date' => 'required|string',
            'Img_U_Id' => 'required|integer|exists:users_master,U_Id',
            'Img_Status' => 'required|string|in:A,I|max:1',
        ]);

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

        // Convert Img_Date to MySQL format
        $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');
            } 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');
        $imagePaths = [];

        // Store images if provided
        if ($request->hasFile('Image') && is_array($request->file('Image'))) {
            foreach ($request->file('Image') as $image) {
                if ($image->isValid()) {
                    $originalName = $image->getClientOriginalName();
                    $filePath = 'classi_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 = 'classi_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;
                }
            }
        }

        // Use transaction for database operation
        DB::beginTransaction();
        try {
            // Create record
            $gallery = ClassiGallary::create([
                'FLC_Id' => $request->input('FLC_Id'),
                'Image' => json_encode($imagePaths),
                'Img_Date' => $imgDate,
                'Img_U_Id' => $request->input('Img_U_Id'),
                'Img_Status' => $request->input('Img_Status'),
            ]);

            DB::commit();

            // Prepare response with full URLs
            $responseData = $gallery->toArray();
            $responseData['Image'] = !empty($imagePaths) ? array_map(function ($path) {
                return url('/storage/' . $path);
            }, $imagePaths) : [];

            return response()->json($responseData, 201);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['error' => 'Failed to create gallery record', 'details' => $e->getMessage()], 500);
        }
    }

    /**
     * Update a ClassiGallary record by Clg_Id.
     */
    public function update(Request $request, $id)
    {
        $gallery = ClassiGallary::find($id);

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

        // Validation rules for Base64 strings
        $validator = Validator::make($request->all(), [
            'FLC_Id' => 'required|integer|exists:free_l_classsified,FLC_Id',
            'Image' => 'nullable|array',
            'Image.*' => ['nullable', 'string', 'regex:/^data:image\/(jpeg|png|jpg|gif|svg);base64,[A-Za-z0-9+\/=]+$/'],
            'Img_Date' => 'required|string',
            'Img_U_Id' => 'required|integer|exists:users_master,U_Id',
            'Img_Status' => 'required|string|in:A,I|max:1',
        ]);

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

        // Convert Img_Date to MySQL format
        $imgDate = $gallery->Img_Date;
        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');
            } 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');
        $imagePaths = json_decode($gallery->Image, true) ?? [];

        // Handle Base64 images if provided
        if ($request->has('Image') && is_array($request->input('Image')) && !empty($request->input('Image'))) {
            // Delete old images
            if (!empty($imagePaths)) {
                foreach ($imagePaths as $oldImagePath) {
                    $fullOldPath = public_path('storage/' . $oldImagePath);
                    if (file_exists($fullOldPath)) {
                        unlink($fullOldPath);
                    }
                }
            }

            // Process new Base64 images
            $imagePaths = [];
            foreach ($request->input('Image') as $index => $base64Image) {
                if (!empty($base64Image)) {
                    // Remove data URI prefix
                    if (preg_match('/^data:image\/(jpeg|png|jpg|gif|svg);base64,/', $base64Image, $matches)) {
                        $extension = $matches[1] === 'svg' ? 'svg' : $matches[1];
                        $base64Image = substr($base64Image, strpos($base64Image, ',') + 1);
                    } else {
                        $extension = 'jpg';
                    }

                    // 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 = 'classi_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;
                }
            }
        }

        // Update the record
        $gallery->update([
            'FLC_Id' => $request->input('FLC_Id'),
            'Image' => json_encode($imagePaths),
            'Img_Date' => $imgDate,
            'Img_U_Id' => $request->input('Img_U_Id'),
            'Img_Status' => $request->input('Img_Status'),
        ]);

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

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

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

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

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

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