<?php

namespace App\Http\Controllers\Api;

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

class TailorGalleryController extends BaseController
{
    /**
     * Get gallery items for the authenticated tailor
     */
    public function index()
    {
        try {
            $gallery = TailorGallery::where('user_id', Auth::id())
                ->orderBy('created_at', 'desc')
                ->get();

            return $this->sendResponse($gallery, 'Data galeri berhasil diambil');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data galeri'], 500);
        }
    }

    /**
     * Store a new gallery item
     */
    public function store(Request $request)
    {
        try {
            // Log request data
            \Log::info('Attempting to store gallery photo', [
                'user_id' => Auth::id(),
                'has_file' => $request->hasFile('photo'),
                'all_data' => $request->all()
            ]);

            $validator = Validator::make($request->all(), [
                'photo' => 'required|image|mimes:jpeg,png,jpg|max:2048',
                'title' => 'nullable|string|max:255',
                'description' => 'nullable|string',
                'category' => 'nullable|string|max:100'
            ]);

            if ($validator->fails()) {
                \Log::warning('Gallery photo validation failed', [
                    'errors' => $validator->errors()->toArray()
                ]);
                return $this->sendError('Error validasi.', $validator->errors(), 422);
            }

            // Upload dan simpan foto
            $photo = $request->file('photo');

            \Log::info('Photo details', [
                'original_name' => $photo->getClientOriginalName(),
                'mime_type' => $photo->getMimeType(),
                'size' => $photo->getSize()
            ]);

            $fileName = 'gallery_' . time() . '_' . Auth::id() . '.' . $photo->getClientOriginalExtension();

            try {
                $photo->storeAs('gallery_photos', $fileName, 'public');
                \Log::info('Photo stored successfully', ['filename' => $fileName]);
            } catch (\Exception $e) {
                \Log::error('Failed to store photo', [
                    'error' => $e->getMessage(),
                    'filename' => $fileName
                ]);
                throw $e;
            }

            // Buat record galeri baru
            $gallery = TailorGallery::create([
                'user_id' => Auth::id(),
                'photo' => '/storage/gallery_photos/' . $fileName,
                'title' => $request->title,
                'description' => $request->description,
                'category' => $request->category
            ]);

            \Log::info('Gallery record created successfully', ['gallery_id' => $gallery->id]);

            return $this->sendResponse($gallery, 'Foto berhasil ditambahkan ke galeri');
        } catch (\Exception $e) {
            \Log::error('Error storing gallery photo', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat menambah foto: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Update gallery item details
     */
    public function update(Request $request, TailorGallery $gallery)
    {
        try {
            // Check ownership
            if ($gallery->user_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk mengubah foto ini'], 403);
            }

            $validator = Validator::make($request->all(), [
                'title' => 'nullable|string|max:255',
                'description' => 'nullable|string',
                'category' => 'nullable|string|max:100'
            ]);

            if ($validator->fails()) {
                return $this->sendError('Error validasi.', $validator->errors(), 422);
            }

            $gallery->update($request->only(['title', 'description', 'category']));

            return $this->sendResponse($gallery, 'Data galeri berhasil diupdate');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengupdate data'], 500);
        }
    }

    /**
     * Delete gallery item
     */
    public function destroy(TailorGallery $gallery)
    {
        try {
            // Check ownership
            if ($gallery->user_id !== Auth::id()) {
                return $this->sendError('Unauthorized.', ['error' => 'Anda tidak memiliki akses untuk menghapus foto ini'], 403);
            }

            // Delete photo file
            $photoPath = str_replace('/storage/', '', $gallery->photo);
            if (Storage::disk('public')->exists($photoPath)) {
                Storage::disk('public')->delete($photoPath);
            }

            $gallery->delete();

            return $this->sendResponse(null, 'Foto berhasil dihapus dari galeri');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat menghapus foto'], 500);
        }
    }

    /**
     * Get gallery items for a specific tailor (public)
     */
    public function getTailorGallery($tailorId)
    {
        try {
            $gallery = TailorGallery::where('user_id', $tailorId)
                ->orderBy('created_at', 'desc')
                ->get();

            return $this->sendResponse($gallery, 'Data galeri penjahit berhasil diambil');
        } catch (\Exception $e) {
            return $this->sendError('Error.', ['error' => 'Terjadi kesalahan saat mengambil data galeri'], 500);
        }
    }
}
