<?php

namespace App\Http\Controllers;

use App\Http\Requests\PropertyRequest;
use App\Models\Property;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class PropertyController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Property::query();

        // Filter by type
        if ($request->has('type') && in_array($request->type, array_keys(Property::getTypes()))) {
            $query->ofType($request->type);
        }

        // Filter by status
        if ($request->has('status')) {
            if ($request->status === 'active') {
                $query->active();
            } elseif ($request->status === 'inactive') {
                $query->where('is_active', false);
            }
        }

        // Filter by display status
        if ($request->has('display_status')) {
            if ($request->display_status === 'mobile') {
                $query->mobileDisplay();
            } elseif ($request->display_status === 'homepage') {
                $query->homepageDisplay();
            }
        }

        // Search by title or description
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('short_description', 'like', "%{$search}%")
                  ->orWhere('full_description', 'like', "%{$search}%");
            });
        }

        $properties = $query->ordered()->paginate(15);
        $types = Property::getTypes();

        return view('properties.index', compact('properties', 'types'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $types = Property::getTypes();
        return view('properties.create', compact('types'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(PropertyRequest $request)
    {
        try {
            $data = $request->validated();

            // Handle card image upload
            if ($request->hasFile('card_image')) {
                $data['card_image'] = $this->uploadImage($request->file('card_image'), 'card');
            }

            // Handle gallery images upload
            if ($request->hasFile('gallery')) {
                $galleryImages = [];
                foreach ($request->file('gallery') as $image) {
                    $galleryImages[] = $this->uploadImage($image, 'gallery');
                }
                $data['gallery'] = $galleryImages;
            }

            // Set default values
            $data['display_on_mobile'] = $request->boolean('display_on_mobile', true);
            $data['display_on_homepage'] = $request->boolean('display_on_homepage', false);
            $data['is_active'] = $request->boolean('is_active', true);
            $data['sort_order'] = $data['sort_order'] ?? 0;

            Property::create($data);

            return redirect()->route('properties.index')
                ->with('success', 'Property created successfully!');

        } catch (\Exception $e) {
            // Clean up uploaded files if creation fails
            if (isset($data['card_image'])) {
                Storage::disk('public')->delete($data['card_image']);
            }
            if (isset($data['gallery'])) {
                foreach ($data['gallery'] as $image) {
                    Storage::disk('public')->delete($image);
                }
            }

            return back()->withErrors(['error' => 'Failed to create property. Please try again.']);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Property $property)
    {
        return view('properties.show', compact('property'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Property $property)
    {
        $types = Property::getTypes();
        return view('properties.edit', compact('property', 'types'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(PropertyRequest $request, Property $property)
    {
        try {
            $data = $request->validated();

            // Handle card image upload
            if ($request->hasFile('card_image')) {
                // Delete old image
                if ($property->card_image) {
                    Storage::disk('public')->delete($property->card_image);
                }
                $data['card_image'] = $this->uploadImage($request->file('card_image'), 'card');
            }

            // Handle gallery images upload
            if ($request->hasFile('gallery')) {
                // Delete old gallery images
                if ($property->gallery) {
                    foreach ($property->gallery as $image) {
                        Storage::disk('public')->delete($image);
                    }
                }
                
                $galleryImages = [];
                foreach ($request->file('gallery') as $image) {
                    $galleryImages[] = $this->uploadImage($image, 'gallery');
                }
                $data['gallery'] = $galleryImages;
            }

            // Set boolean values
            $data['display_on_mobile'] = $request->boolean('display_on_mobile');
            $data['display_on_homepage'] = $request->boolean('display_on_homepage');
            $data['is_active'] = $request->boolean('is_active');

            $property->update($data);

            return redirect()->route('properties.index')
                ->with('success', 'Property updated successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to update property. Please try again.']);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Property $property)
    {
        try {
            // Delete card image
            if ($property->card_image) {
                Storage::disk('public')->delete($property->card_image);
            }

            // Delete gallery images
            if ($property->gallery) {
                foreach ($property->gallery as $image) {
                    Storage::disk('public')->delete($image);
                }
            }

            $property->delete();

            return redirect()->route('properties.index')
                ->with('success', 'Property deleted successfully!');

        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'Failed to delete property. Please try again.']);
        }
    }

    /**
     * Toggle the active status of a property.
     */
    public function toggleActive(Property $property)
    {
        $property->toggleActive();
        
        $status = $property->isActive() ? 'activated' : 'deactivated';
        
        return redirect()->route('properties.index')
            ->with('success', "Property {$status} successfully!");
    }

    /**
     * Toggle the mobile display status of a property.
     */
    public function toggleMobileDisplay(Property $property)
    {
        $property->toggleMobileDisplay();
        
        $status = $property->isDisplayedOnMobile() ? 'enabled' : 'disabled';
        
        return redirect()->route('properties.index')
            ->with('success', "Mobile display {$status} successfully!");
    }

    /**
     * Toggle the homepage display status of a property.
     */
    public function toggleHomepageDisplay(Property $property)
    {
        $property->toggleHomepageDisplay();
        
        $status = $property->isDisplayedOnHomepage() ? 'enabled' : 'disabled';
        
        return redirect()->route('properties.index')
            ->with('success', "Homepage display {$status} successfully!");
    }

    /**
     * Update the sort order of properties.
     */
    public function updateSortOrder(Request $request)
    {
        $request->validate([
            'properties' => 'required|array',
            'properties.*.id' => 'required|exists:properties,id',
            'properties.*.sort_order' => 'required|integer|min:0',
        ]);

        foreach ($request->properties as $propertyData) {
            Property::where('id', $propertyData['id'])
                ->update(['sort_order' => $propertyData['sort_order']]);
        }

        return response()->json(['success' => true]);
    }

    /**
     * Upload image to storage.
     */
    private function uploadImage($file, $prefix): string
    {
        $filename = $prefix . '_' . time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
        $path = $file->storeAs('properties', $filename, 'public');
        
        return $path;
    }
} 