<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\ProductSubCategory;
use Illuminate\Support\Facades\DB;

class ProductSubCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:sanctum']);
    }

    public function index()
    {
        try {
            $subCategories = ProductSubCategory::with(['productCategory'])->get();

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch sub categories',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function store(Request $request)
    {
        DB::beginTransaction();

        try {
            $request->validate([
                'name' => 'required|string|max:255',
                'description' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                'product_category_id' => 'required|exists:product_categories,id',
            ]);

            $imagePath = null;

            if ($request->hasFile('image')) {
                $imagePath = $this->uploadFile($request->file('image'));
            }

            $subCategory = ProductSubCategory::create([
                'name' => $request->name,
                'description' => $request->description,
                'image' => $imagePath,
                'product_category_id' => $request->product_category_id,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Sub Category created successfully',
                'data' => $subCategory
            ], 201);

        } catch (\Exception $e) {

            DB::rollBack();

            if (isset($imagePath) && $imagePath && file_exists(public_path(parse_url($imagePath, PHP_URL_PATH)))) {
                unlink(public_path(parse_url($imagePath, PHP_URL_PATH)));
            }

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

    public function update(Request $request, $id)
    {
        DB::beginTransaction();

        try {
            $subCategory = ProductSubCategory::find($id);

            if (!$subCategory) {
                return response()->json([
                    'success' => false,
                    'message' => 'Sub Category not found'
                ], 404);
            }

            $request->validate([
                'name' => 'sometimes|required|string|max:255',
                'description' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                'product_category_id' => 'sometimes|required|exists:product_categories,id',
            ]);

            $imagePath = $subCategory->image;

            if ($request->hasFile('image')) {

                if ($subCategory->image) {
                    $this->deleteFile($subCategory->image);
                }

                $imagePath = $this->uploadFile($request->file('image'));
            }

            $subCategory->update([
                'name' => $request->name ?? $subCategory->name,
                'description' => $request->description ?? $subCategory->description,
                'product_category_id' => $request->product_category_id ?? $subCategory->product_category_id,
                'image' => $imagePath,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Sub Category updated successfully',
                'data' => $subCategory
            ]);

        } catch (\Exception $e) {

            DB::rollBack();

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

    public function destroy($id)
    {
        DB::beginTransaction();

        try {
            $subCategory = ProductSubCategory::find($id);

            if (!$subCategory) {
                return response()->json([
                    'success' => false,
                    'message' => 'Sub Category not found'
                ], 404);
            }

            if ($subCategory->image) {
                $this->deleteFile($subCategory->image);
            }

            $subCategory->delete();

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Sub Category deleted successfully'
            ]);

        } catch (\Exception $e) {

            DB::rollBack();

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

    private function uploadFile($file)
    {
        if (!$file || !$file->isValid()) return null;

        $fileName = time() . '_' . $file->getClientOriginalName();

        $file->move(
            public_path("storage/product_sub_category"),
            $fileName
        );

        return url("storage/product_sub_category/$fileName");
    }

    private function deleteFile($fileUrl)
    {
        if (!$fileUrl) return;

        $path = public_path(parse_url($fileUrl, PHP_URL_PATH));

        if (file_exists($path)) {
            unlink($path);
        }
    }
}