<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Content;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class CatalogController extends Controller
{
    public function index()
    {
        // Ambil jumlah maksimal item dari database (default 10)
        $maxItems = (int) Content::getValue('cv_catalog_max_items', 10);
        
        // Generate semua keys untuk item 1 sampai maxItems
        $keys = ['cv_catalog_description'];
        for ($i = 1; $i <= $maxItems; $i++) {
            $keys[] = 'cv_catalog_' . $i . '_title';
            $keys[] = 'cv_catalog_' . $i . '_price';
            $keys[] = 'cv_catalog_' . $i . '_image';
        }

        $contents = Content::whereIn('key', $keys)->get();

        return view('admin.catalog', compact('contents', 'maxItems'));
    }

    public function update(Request $request)
    {
        // Ambil jumlah maksimal item dari database (default 10)
        $maxItems = (int) Content::getValue('cv_catalog_max_items', 10);
        
        // Validasi input
        $rules = [
            'contents' => 'array',
            'contents.*.key' => 'required|string',
            'contents.*.value' => 'required|string',
        ];
        
        // Tambahkan validasi untuk semua gambar (10MB = 10240 KB)
        for ($i = 1; $i <= $maxItems; $i++) {
            $rules['cv_catalog_' . $i . '_image'] = 'nullable|image|mimes:jpeg,png,jpg,gif,bmp,webp|max:10240';
        }
        
        $validated = $request->validate($rules);

        // ✅ LANGKAH 1: HAPUS GAMBAR YANG DIPILIH USER (SEBELUM SIMPAN DATA BARU)
        for ($i = 1; $i <= $maxItems; $i++) {
            if ($request->has('remove_image_' . $i)) {
                $key = 'cv_catalog_' . $i . '_image';
                $oldImage = Content::where('key', $key)->value('value');
                
                // Hapus file dari storage jika ada
                if ($oldImage && $oldImage !== 'default-cv.jpg' && !empty(trim($oldImage))) {
                    Storage::disk('public')->delete('cv-catalog/' . $oldImage);
                }
                
                // Kosongkan nilai di database
                Content::updateOrCreate(
                    ['key' => $key],
                    ['value' => '']
                );
            }
        }

        // Simpan semua konten (title & price)
        foreach ($validated['contents'] as $content) {
            Content::updateOrCreate(
                ['key' => $content['key']],
                ['value' => $content['value']]
            );
        }

        // Handle upload gambar untuk semua item (jika ada upload baru)
        for ($i = 1; $i <= $maxItems; $i++) {
            if ($request->hasFile('cv_catalog_' . $i . '_image')) {
                $this->saveImage($request->file('cv_catalog_' . $i . '_image'), 'cv_catalog_' . $i . '_image');
            }
        }

        return redirect()->back()->with('success', 'CV Catalog updated successfully!');
    }

    private function saveImage($image, $key)
    {
        // Pastikan folder cv-catalog ada
        if (!Storage::disk('public')->exists('cv-catalog')) {
            Storage::disk('public')->makeDirectory('cv-catalog', 0755, true);
        }

        // Generate nama file unik
        $extension = $image->getClientOriginalExtension();
        $filename = $key . '-' . time() . '.' . $extension;
        
        // Simpan ke storage
        $path = $image->storeAs('cv-catalog', $filename, 'public');
        
        // ✅ SOLUSI UTAMA: HAPUS _image GANDA
        Content::updateOrCreate(
            ['key' => $key], // HANYA $key SAJA (TANPA _image TAMBAHAN)
            ['value' => $filename]
        );
        
        // ✅ HAPUS _image GANDA JUGA DI BAGIAN HAPUS GAMBAR LAMA
        $oldImage = Content::where('key', $key)
                      ->where('value', '!=', $filename)
                      ->where('value', '!=', 'default-cv.jpg')
                      ->value('value');
        
        if ($oldImage && Storage::disk('public')->exists('cv-catalog/' . $oldImage)) {
            Storage::disk('public')->delete('cv-catalog/' . $oldImage);
        }
    }
}