<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\Country;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;

class CountryController extends Controller
{
    public function country()
    {
        $records   =  Country::orderBy('name', 'ASC')->get();
        return view('backend.country.list', compact('records'));
    }

    public function addCountry($id = '')
    {
        $record = '';
        if ($id > 0) {
            $record = Country::WHere('id', $id)->first();
        }
        return view('backend.country.add_edit', compact('record'));
    }

    public function storeUpdateCountry(Request $request)
    {
        $input     = $request->all();
        $id        = isset($input['id']) ? $input['id'] : 0;

        $dataArr = [];
        foreach ($input as $key => $val) {
            if ($key != '_token' && $key != 'id' && $key != 'flag_image')
                $dataArr[$key] = $val;
        }

        if ($request->file('flag_image') != '') {
            $image = $request->file('flag_image');
            $imageName = 'product_image' . time() . '_' . str_replace(' ', '_', $image->getClientOriginalName());
            $image->move(public_path('/uploads/country/'), $imageName);
            $imageUrl = URL::to('/') . '/uploads/country/' . $imageName;
            $dataArr['image'] = $imageUrl;
        }
        if ($id == 0 || $id == '') {
            $request->validate([
                'name'          =>  "required|unique:countries,name",
                'phone_code'    =>  "required|unique:countries,phone_code",
                'currency_name' =>  "required|unique:countries,currency_name",
                'currency_code' =>  "required|unique:countries,currency_code",
            ]);
           $insert = Country::create($dataArr);
           if($insert['id'] > 0)
           {
               return redirect()->route('country')->with('success', 'Country Saved Successfully');
           }else{
               return redirect()->route('country')->with('error', 'Something went wrong!');
           }
           
        } else {
            $request->validate([
                'name'          =>  "required",
                'phone_code'    =>  "required",
                'currency_name' =>  "required",
                'currency_code' =>  "required",
            ]);
            $update = Country::Where('id',$id)->update($dataArr);
            return redirect()->route('country')->with('success', 'Country Updated Successfully');;
        }        
    }
}
