<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PropertyPhotos;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class PropertyPhotosController extends Controller
{
    public function index()
    {
        try {

            $photos = PropertyPhotos::with('property')
                ->latest('created_at')
                ->paginate(10);

            return response()->json([
                'success' => true,
                'data'    => $photos
            ], 200);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch assets property: ' . $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_property' => 'nullable|exists:properties,id',
            'file'        => 'required|mimes:jpg,jpeg,png,webp,mp4,mov,avi,webm|max:20480',
            'caption'     => 'nullable|string|max:255',
            'is_main'     => 'nullable|boolean',
        ]);

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

        try {

            $file = $request->file('file');
            $ext  = strtolower($file->getClientOriginalExtension());
            $fileName = time() . '_' . uniqid() . '.' . $ext;

            $isVideo = in_array($ext, ['mp4','mov','avi','webm']);

            $folder = $isVideo
                ? 'storage/videos/property/'
                : 'storage/images/property/';

            $file->move(public_path($folder), $fileName);

            $filePath = Storage::url(
                str_replace('storage/', '', $folder) . $fileName
            );

            /*
            |--------------------------------------------------------------------------
            | Hitung Urutan Berdasarkan Scope
            |--------------------------------------------------------------------------
            */
            if ($request->id_property) {

                $lastOrder = PropertyPhotos::where('id_property', $request->id_property)
                    ->max('urutan') ?? 0;

            } else {

                $lastOrder = PropertyPhotos::whereNull('id_property')
                    ->max('urutan') ?? 0;
            }

            $urutanBaru = (int) $lastOrder + 1;

            /*
            |--------------------------------------------------------------------------
            | Reset is_main Hanya Dalam Scope yang Sama
            |--------------------------------------------------------------------------
            */
            if ($request->is_main) {

                if ($request->id_property) {

                    PropertyPhotos::where('id_property', $request->id_property)
                        ->update(['is_main' => false]);

                } else {

                    PropertyPhotos::whereNull('id_property')
                        ->update(['is_main' => false]);
                }
            }

            /*
            |--------------------------------------------------------------------------
            | Simpan Data
            |--------------------------------------------------------------------------
            */
            $photo = PropertyPhotos::create([
                'id_property' => $request->id_property,
                'file'        => $filePath,
                'caption'     => $request->caption,
                'urutan'      => $urutanBaru,
                'is_main'     => $request->is_main ?? false,
                'type'        => $isVideo ? 'video' : 'image',
            ]);

            return response()->json([
                'success' => true,
                'data'    => $photo->load('property')
            ], 201);

        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function setMain($id)
    {
        try {
            $photo = PropertyPhotos::findOrFail($id);
            PropertyPhotos::where('id_property', $photo->id_property)->update(['is_main' => false]);
            $photo->is_main = true;
            $photo->save();

            return response()->json(['success' => true, 'message' => 'Foto/video utama berhasil diperbarui.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            $photo = PropertyPhotos::findOrFail($id);
            $path = public_path($photo->file);
            if (file_exists($path)) {
                unlink($path);
            }
            $photo->delete();

            return response()->json(['success' => true, 'message' => 'File berhasil dihapus.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}
