<?php

namespace App\Http\Controllers\Superadmin;

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

class BolgeTanimlamaController extends Controller
{
    public function index()
    {
        $iller = DB::table('kurum_iller')->get();
        $ilceler = DB::table('kurum_ilceler')->get();
        $beldeler = DB::table('kurum_beldeler')->get();
        $mahalleler = DB::table('kurum_mahalleler')->get();

        return view('superadmin.bolge-tanimlamalari.index', compact('iller', 'ilceler', 'beldeler', 'mahalleler'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:il,ilce,belde,mahalle',
            'parent_id' => 'nullable|integer'
        ]);

        $tableMapping = [
            'il' => 'kurum_iller',
            'ilce' => 'kurum_ilceler',
            'belde' => 'kurum_beldeler',
            'mahalle' => 'kurum_mahalleler',
        ];

        $tableName = $tableMapping[$request->type];
        $data = ['ad' => $request->name];

        if ($request->type === 'ilce') $data['il_id'] = $request->parent_id;
        if ($request->type === 'belde') $data['ilce_id'] = $request->parent_id;
        if ($request->type === 'mahalle') $data['belde_id'] = $request->parent_id;

        $id = DB::table($tableName)->insertGetId($data);

        return response()->json(['success' => true, 'id' => $id, 'name' => $request->name]);
    }

    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|integer',
            'name' => 'required|string|max:255',
            'type' => 'required|in:il,ilce,belde,mahalle',
        ]);

        $tableMapping = [
            'il' => 'kurum_iller',
            'ilce' => 'kurum_ilceler',
            'belde' => 'kurum_beldeler',
            'mahalle' => 'kurum_mahalleler',
        ];
        $tableName = $tableMapping[$request->type];

        DB::table($tableName)->where('id', $request->id)->update(['ad' => $request->name]);

        return response()->json(['success' => true]);
    }

    public function destroy(Request $request)
    {
        $request->validate([
            'id' => 'required|integer',
            'type' => 'required|in:il,ilce,belde,mahalle',
        ]);

        $tableMapping = [
            'il' => 'kurum_iller',
            'ilce' => 'kurum_ilceler',
            'belde' => 'kurum_beldeler',
            'mahalle' => 'kurum_mahalleler',
        ];
        $tableName = $tableMapping[$request->type];

        // Alt öğeleri silme mantığı eklenebilir
        DB::table($tableName)->where('id', $request->id)->delete();

        return response()->json(['success' => true]);
    }
}
