<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Country;
use Yajra\DataTables\Facades\DataTables;

class SettingsController extends Controller
{
    public function addCountry(Request $request)
    {
        $res = Country::insert([
            'name' => $request->input('name'),
            'currency' => $request->input('currency'),
            'country_code' => $request->input('country_code'),
        ]);


        if ($res == 1)
            return redirect()->back()->with('success', 'Country added successfully');
        else
            return redirect()->back()->with('error', 'Something went wrong');
    }

    public function getCountry()
    {
        $users = Country::orderBy('id', 'DESC')->get();

        return DataTables::of($users)
            ->addIndexColumn()
            ->addColumn('name', function ($data) {
                return   $data->name;
            })
             ->addColumn('country_code', function ($data) {
                return   $data->country_code;
            })
            ->addColumn('currency', function ($data) {
                return   $data->currency;
            })
            ->addColumn('action', function ($row) {
                return '<a href="" class="btn btn-sm btn-purple editCountry" data-id="'.$row->id.'">Edit</a>
                <a href="" class="btn btn-sm btn-danger deleteCountry" data-id="' . $row->id . '">Delete</a>';
            })
            ->escapeColumns([])
            ->make(true);
    }

    
    // Delete country (AJAX)
    public function destroy($id)
    {
        $country = Country::findOrFail($id);
        $country->delete();
        return response()->json(['success' => 'Country deleted successfully.']);
    }

    public function update(Request $request, $id)
{
    $request->validate([
        'name' => 'required|string|max:100',
        'currency' => 'required|string|max:5',
        'country_code' => 'required|string|max:5',
    ]);

    //$country = Country::findOrFail($id);
    Country::where('id',$id)->update([
        'name' => $request->name,
        'currency' => $request->currency,
        'country_code' => $request->input('country_code'),
    ]);

    return response()->json(['success' => 'Country updated successfully.']);
}

}
