<?php
namespace App\Http\Controllers;

use App\Helpers\Response;
use App\Http\Controllers\Controller;
use App\Models\City;
use App\Models\Neighborhood;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class NeighborhoodController extends Controller
{

    public function __construct()
    {
        $this->middleware(['permission:neighborhood_view'], ['only' => 'index']);
        $this->middleware(['permission:neighborhood_create'], ['only' => 'store']);
        $this->middleware(['permission:neighborhood_edit'], ['only' => 'update']);
        $this->middleware(['permission:neighborhood_delete'], ['only' => 'destroy']);
    }

    // Show All Rows
    public function index()
    {

        // Search Attr
        $qCity = request('city');
        $qName = request('name');

        $sqlQuery = Neighborhood::with(['by', 'city'])->orderByDesc('id');
        // ->where('city_id',  request('city'))->where('name', 'like', '%' . request('name') . '%')

        $sqlQuery = $qCity != null ? $sqlQuery->where('city_id', request('city')) : $sqlQuery;
        $sqlQuery = $qName != null ? $sqlQuery->where('name', 'like', '%' . request('name') . '%') : $sqlQuery;

        $rows = $sqlQuery->paginate(25);

        $cities = City::orderByDesc('id')->get(['id', 'name'])->toArray();

        // Check IF Have Edit
        $id = intval(request('edit'));

        if ($id != 0) {

            $editRow = Neighborhood::where('id', $id)->first()->toArray();
            // Form Update Options
            $formOption = [
                'panelTitle'   => 'تحديث بيانات حي',
                'submitButton' => 'تحديث',
                'formAction'   => route('neighborhood.update'),
            ];

            if ($editRow == null) {
                return redirect(adminUrl('neighborhoods'))->with('warning', 'البيانات المطلوبة غير متاحة في النظام');
            }

        } else {

            // Form Create Options
            $editRow    = [];
            $formOption = [
                'panelTitle'   => 'اضافة حي جديد',
                'submitButton' => 'اضافة',
                'formAction'   => route('neighborhood.store'),
            ];
        }

        return view('dashboard.neighborhoods.index', compact('rows', 'cities', 'editRow', 'formOption'));
    }

    // Insert New Row
    public function store(Request $request, Neighborhood $neighborhoods)
    {

        //
        $data = $request->validate([
            'name'    => 'required|max:150|min:2|unique:' . $neighborhoods->table . ',name',
            'city_id' => 'required|in:' . inValidateByPluck(City::get()->pluck('id')),
            'desc'    => 'nullable|max:1500',
        ]);

        // Add New Attr
        $data['created_by'] = adminId();

        // Insert
        $neighborhoods->create($data);

        return Response::success('تم اضافة المدينة بنجاح...', ['style' => 'toastr', 'reset' => true, 'reload' => true, 'time_out' => 1]);
    }

    // Update Row
    public function update(Request $request, Neighborhood $neighborhoods)
    {

        $row = Neighborhood::where('id', $request->id)->first();

        // Check If Not Exists in db
        if ($row == null) {
            return Response::error('البيانات المطلوبة غير متوفرة في النظام', ['style' => 'toastr']);
        }

        // Validate Data
        $data = $request->validate([
            'name'    => 'required|max:150|min:2|unique:' . $neighborhoods->table . ',name,' . $row->id,
            'city_id' => 'required|in:' . inValidateByPluck(City::get()->pluck('id')),
            'desc'    => 'nullable|max:1500',
        ]);

        // Insert
        $row->update($data);

        // Return Message
        return Response::success('تم تحديث المدينة بنجاح...', ['style' => 'toastr', 'redirect' => adminUrl('neighborhoods'), 'reload' => true, 'time_out' => 1]);
    }

    // Delete Row
    public function destroy()
    {
        // Get Row And Check IF IN Database
        $row = Neighborhood::find(request('id'));

        // Check If Not Exist The Row IN Database
        if (empty($row)) {
            // Message
            return Response::error('هذه العملية غير مصرح بها، وقد لا تكون البيانات المطلوبة متاحة في النظام', ['style' => 'toastr']);
        } else {
            // Delete From DB
            $row->delete();
            //Message
            return Response::success('تم حذف البيانات بنجاح', ['style' => 'toastr']);
        }
    }

    public function getNeighborhoods(Neighborhood $neighborhoods)
    {
        $response = DB::table($neighborhoods->table)->orderBy('name', 'ASC')->where('city_id', request('city_id'))->pluck('id', 'name');

        if (count($response) == 0) {
            $response = [
                'status'  => 'empty',
                'message' => 'لا يوجد أحياء مرتبطة بهذه المدينة حتى الآن !',
            ];
        }
        return response()->json($response);
    }
}
