<?php

namespace App\Http\Controllers\Api;

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

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

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

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

            $imagePath = null;

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

            $industry = Industry::create([
                'name' => $request->name,
                'image' => $imagePath,
                'description' => $request->description,
                'user_id' => $request->user()->id,
            ]);

            DB::commit();

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

    public function index()
    {
        try {
            $industries = Industry::all();

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

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

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

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

        $industry = Industry::find($id);

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

        $imagePath = $industry->image_url;

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

            if ($industry->image_url) {
                $this->deleteIndustryFile($industry->image_url);
            }

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

        $industry->update([
            'name' => $request->name,
            'image_url' => $imagePath,
            'description' => $request->description,
        ]);

        DB::commit();

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

    } catch (\Exception $e) {

        DB::rollBack();

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

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

        try {
            $industry = Industry::findOrFail($id);

            if ($industry->image) {
                $this->deleteIndustryFile($industry->image);
            }

            $industry->delete();

            DB::commit();

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

        } catch (\Exception $e) {

            DB::rollBack();

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

    private function uploadIndustryFile($file)
    {
        if (! $file) {
            return null;
        }

        if (! $file->isValid()) {
            throw new \Exception($file->getErrorMessage());
        }

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

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

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

    private function deleteIndustryFile($fileUrl)
    {
        $path = public_path(
            parse_url($fileUrl, PHP_URL_PATH)
        );

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