<?php

namespace App\Http\Controllers\Api;

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

class ProductCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'auth:sanctum'
        ]);
    }
    
    public function store(Request $request)
    {
        DB::beginTransaction();

        try {
            $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                'description' => 'nullable|string',
                'industry_id' => 'required|exists:industries,id',
                'sub_industry_id' => 'nullable|exists:sub_industries,id',
            ]);

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


            $imagePath = null;

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

            $productCategory = ProductCategory::create([
                'name' => $request->name,
                'image' => $imagePath,
                'description' => $request->description,
                'industry_id' => $request->industry_id,
                'sub_industry_id' => $request->sub_industry_id,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Product Category created successfully',
                'data' => $productCategory->load('industry', 'subIndustry')
            ], 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' => 'Product Category creation failed',
                'error' => $e->getMessage()
            ], 500);
        }
    }

    public function index()
    {
        try {
            $categories = ProductCategory::with(['industry', 'subIndustry'])->get();

            return response()->json([
                'success' => true,
                'data' => $categories->load('industry', 'subIndustry')
            ]);

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

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

        try {
                        $validator = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
                'description' => 'nullable|string',
                'industry_id' => 'required|exists:industries,id',
                'sub_industry_id' => 'nullable|exists:sub_industries,id',
            ]);

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

            $category = ProductCategory::find($id);

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

            $imagePath = $category->image;

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

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

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

            $category->update([
                'name' => $request->name,
                'image' => $imagePath,
                'description' => $request->description,
                'industry_id' => $request->industry_id,
                'sub_industry_id' => $request->sub_industry_id,
            ]);

            DB::commit();

            return response()->json([
                'success' => true,
                'message' => 'Product Category updated successfully',
                'data' => $category->load('industry', 'subIndustry')
            ]);

        } catch (\Exception $e) {

            DB::rollBack();

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

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

        try {
            $category = ProductCategory::find($id);

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

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

            $category->delete();

            DB::commit();

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

        } catch (\Exception $e) {

            DB::rollBack();

            return response()->json([
                'success' => false,
                'message' => 'Product 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_category"),
            $fileName
        );

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

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

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

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