<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PdCategory;
use Illuminate\Http\Request;

class PdCategoryController extends Controller
{
    // লিস্ট
    public function index()
    {
        $query = PdCategory::query()->orderBy('id', 'desc');

        if (request('q')) {
            $q = trim(request('q'));
            $query->where(function ($w) use ($q) {
                $w->where('name', 'like', "%{$q}%")
                  ->orWhere('slug', 'like', "%{$q}%");
            });
        }

        $categories = $query->paginate(20)->withQueryString();
        return view('admin.pd_categories.index', compact('categories'));
    }

    // এড ফর্ম
    public function create()
    {
        return view('admin.pd_categories.create');
    }

    // সেভ
    public function store(Request $request)
    {
        $request->validate([
            'name'   => ['required','max:191'],
            'photo'  => ['nullable','image','mimes:jpg,jpeg,png,webp','max:2048'],
            'status' => ['nullable','in:0,1'],
        ]);

        $name = $request->input('name');
        $slug = $this->makeSlug($name);

        $photoPath = null;
        if ($request->hasFile('photo')) {
            $photoPath = $this->uploadImage($request->file('photo'), $slug);
        }

        PdCategory::create([
            'name'   => $name,
            'slug'   => $slug,
            'photo'  => $photoPath, // '/images/e-commerce/category/...' (relative public path)
            'status' => $request->boolean('status') ? 1 : 0,
        ]);

        return redirect()
            ->route('admin.pd-categories.index')
            ->with('success', 'Category created successfully.');
    }

    // এডিট ফর্ম
    public function edit($id)
    {
        $category = PdCategory::findOrFail($id);
        return view('admin.pd_categories.edit', compact('category'));
    }

    // আপডেট
    public function update(Request $request, $id)
    {
        $category = PdCategory::findOrFail($id);

        $request->validate([
            'name'   => ['required','max:191'],
            'photo'  => ['nullable','image','mimes:jpg,jpeg,png,webp','max:2048'],
            'status' => ['nullable','in:0,1'],
        ]);

        $name = $request->input('name');

        // name বদলালে নতুন slug, কিন্তু ইউনিক রাখি
        $slug = $category->name === $name
            ? $category->slug
            : $this->makeSlug($name, $category->id);

        $photoPath = $category->photo;

        if ($request->hasFile('photo')) {
            // পুরনো ফটো ডিলিট (full URL/relative—দুই কেসেই কাজ করবে)
            $this->deletePhotoIfExists($photoPath);

            // নতুন ফটো আপলোড
            $photoPath = $this->uploadImage($request->file('photo'), $slug);
        }

        $category->update([
            'name'   => $name,
            'slug'   => $slug,
            'photo'  => $photoPath, // '/images/e-commerce/category/...' (relative)
            'status' => $request->boolean('status') ? 1 : 0,
        ]);

        return redirect()
            ->route('admin.pd-categories.index')
            ->with('success', 'Category updated successfully.');
    }

    // ডিলিট
    public function destroy($id)
    {
        $category = PdCategory::findOrFail($id);

        // পুরনো ফটো থাকলে ডিলিট (full URL/relative—দুই কেসেই)
        $this->deletePhotoIfExists($category->photo);

        $category->delete();

        return redirect()
            ->route('admin.pd-categories.index')
            ->with('success', 'Category deleted.');
    }

    // ===== Helpers =====

    /**
     * ডকুমেন্ট রুট-ভিত্তিক ক্যাটাগরি ইমেজ ডিরেক্টরি
     * e.g. <docroot>/images/e-commerce/category
     */
    private function categoryDirAbs(): string
    {
        return ensure_public_directory('images/e-commerce/category');
    }

    /**
     * পুরনো ফটো ডিলিট (full URL বা relative—দুইটাই কভার)
     */
    private function deletePhotoIfExists(?string $photo): void
    {
        if (!$photo) return;

        $absDir = rtrim($this->categoryDirAbs(), '/');

        // যদি full URL হয়, URL থেকে path বের করি
        // উদাহরণ: https://domain.com/images/e-commerce/category/xyz.jpg
        $pathFromUrl = parse_url($photo, PHP_URL_PATH); // '/images/e-commerce/category/xyz.jpg'
        $candidate   = $pathFromUrl ?: $photo;          // path বা relative

        $absFile = public_asset_path($candidate);

        // সেফটি: শুধু আমাদের টার্গেট ডিরেক্টরির ফাইল হলে ডিলিট
        if (strpos($absFile, $absDir) === 0 && is_file($absFile)) {
            @unlink($absFile);
        }
    }

    private function makeSlug($name, $ignoreId = null)
    {
        $base = $this->slugify($name);
        $slug = $base;
        $i = 1;

        while (
            PdCategory::where('slug', $slug)
                ->when($ignoreId, fn($q) => $q->where('id', '!=', $ignoreId))
                ->exists()
        ) {
            $slug = $base . '-' . $i;
            $i++;
        }

        return $slug;
    }

    private function slugify($str)
    {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $str), '-'));
        $slug = preg_replace('/-+/', '-', $slug);
        return $slug ?: uniqid();
    }

    /**
     * ফটো আপলোড: ডকুমেন্ট রুটে সেভ + DB-তে relative public path
     * রিটার্ন: '/images/e-commerce/category/filename.ext'
     */
    private function uploadImage($file, $slug): string
    {
        $dir = $this->categoryDirAbs();

        $ext      = $file->getClientOriginalExtension();
        $filename = time() . '_' . $slug . '.' . $ext;

        // Move to absolute dir (document root)
        $file->move($dir, $filename);
        optimize_uploaded_image($dir . DIRECTORY_SEPARATOR . $filename);

        // DB-তে relative public path সেভ করি (UI-তে asset(ltrim($path,'/')) ব্যবহার করুন)
        return '/images/e-commerce/category/' . $filename;
    }
}
