<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ReportType;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class ReportTypeController extends Controller
{
    public function index()
    {
        $types = [];
        return view('admin.reporttypes.index', compact('types'));

    }

    public function getReportTypeList(Request $request){
        $sqlBuilder = ReportType::select([
            'report_types.id',
            'report_types.name',
            'report_types.name_ar',
        ]);

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('report_types.name', 'ilike', "%" . $request->search['value'] . "%")
                ->orWhere('report_types.name_ar', 'ilike', "%" . $request->search['value'] . "%");
            }
        })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . route('admin.report_types.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.report_types.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['action'])
            ->make(true);
    }

    public function create(){
        $type = "";

        return view('admin.reporttypes.create', compact('type'));

    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'nullable|string|max:255',
        ];
    
        $validator = Validator::make($request->all(), $rules);
    
        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }
    
        if ($request->id) {
            $type = ReportType::find($request->id);
    
            if (!$type) {
                return response()->json(['status' => 'error', 'message' => 'Emirate not found'], 404);
            }
    
            $existingType = ReportType::where('name', $request->name)
                ->where('id', '!=', $request->id)
                ->first();
    
            if ($existingType) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Type name already exists.']
                    ]
                ], 422);
            }
    
            $type->name = $request->name;
            $type->name_ar = $request->name_ar;
            $type->save();
    
            return response()->json(['status' => 'success', 'message' => 'Report Type updated successfully']);
        } else {
            $existingType = ReportType::where('name', $request->name)->first();
    
            if ($existingType) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'name' => ['The Type name already exists.']
                    ]
                ], 422);
            }
    
            $type = ReportType::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
            ]);

            $type->save();
    
            return response()->json(['status' => 'success', 'message'  => 'Report Type added successfully', 'emirate' => $type]);
        }
    }
  
    public function edit($id) {
        $type = ReportType::findOrFail($id);
        return view('admin.reporttypes.create', compact('type'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = ReportType::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Report Type deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Report Type not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }
}
