<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RegionController extends Controller
{
    public function index()
    {
        $regions = DB::table('regions')->get();
        $region = null;
        return view('regions.index', compact('regions', 'region'));
    }

    public function create() { return view('regions.create'); }

    public function store(Request $request)
    {
        DB::table('regions')->insert(['uz' => $request->uz ?? $request->name, 'ru' => $request->ru ?? $request->name, 'cr' => $request->cr ?? $request->name, 'created_at' => now(), 'updated_at' => now()]);
        return redirect()->route('regions.index');
    }

    public function show($id)
    {
        $region = DB::table('regions')->find($id);
        return view('regions.show', compact('region'));
    }

    public function edit($id)
    {
        $region = DB::table('regions')->find($id);
        return view('regions.edit', compact('region'));
    }

    public function update(Request $request, $id)
    {
        DB::table('regions')->where('id', $id)->update(['uz' => $request->uz ?? $request->name, 'ru' => $request->ru ?? $request->name, 'cr' => $request->cr ?? $request->name, 'updated_at' => now()]);
        return redirect()->route('regions.index');
    }

    public function destroy($id)
    {
        DB::table('regions')->delete($id);
        return redirect()->route('regions.index');
    }

    public function districts($id)
    {
        $districts = DB::table('districts')->where('region_id', $id)->get();
        return response()->json($districts);
    }
}
