<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\State;
use App\Exports\ExportState;
use Maatwebsite\Excel\Facades\Excel;
use Auth, DB, Mail, Validator, File, DataTables, Exception;
class StateController extends Controller{
    /** construct */
        public function __construct(){
            $this->middleware('permission:state-create', ['only' => ['create']]);
            $this->middleware('permission:state-edit', ['only' => ['edit']]);
            $this->middleware('permission:state-view', ['only' => ['view']]);
            $this->middleware('permission:state-delete', ['only' => ['delete']]);
        }
    /** construct */

    /** index */
        public function index(Request $request){
            if ($request->ajax()) {
            $data = State::select('id', 'name', 'status')
                ->where('status', '!=', 'deleted')
                ->orderBy('id', 'desc');

            return Datatables::of($data)
                ->addIndexColumn()
                ->editColumn('status', function ($data) {
                    if ($data->status == 'active') {
                        return '<span class="badge badge-success">Active</span>';
                    } elseif ($data->status == 'inactive') {
                        return '<span class="badge badge-warning">Inactive</span>';
                    } elseif ($data->status == 'deleted') {
                        return '<span class="badge badge-danger">Deleted</span>';
                    } else {
                        return '-';
                    }
                })
                ->addColumn('action', function ($data) {
                    $return = '<div class="btn-group">';

                    if (auth()->user()->can('state-view')) {
                        $return .= '<a href="'.route('state.view', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                        <i class="fa fa-eye"></i>
                                    </a> &nbsp;';
                    }

                    if (auth()->user()->roles[0]['name'] == 'admin' && auth()->user()->can('state-edit')) {
                        $return .= '<a href="'.route('state.edit', ['id' => base64_encode($data->id)]).'" class="btn btn-default btn-xs">
                                        <i class="fa fa-edit"></i>
                                    </a> &nbsp;';
                    }

                    if (auth()->user()->can('state-delete')) {
                        $return .= '<a href="javascript:;" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
                                        <i class="fa fa-bars"></i>
                                    </a> &nbsp;
                                    <ul class="dropdown-menu">
                                        <li><a class="dropdown-item change-status" href="javascript:;" data-status="active" data-id="' . base64_encode($data->id) . '">Active</a></li>
                                        <li><a class="dropdown-item change-status" href="javascript:;" data-status="inactive" data-id="' . base64_encode($data->id) . '">Inactive</a></li>
                                        <li><a class="dropdown-item change-status" href="javascript:;" data-status="deleted" data-id="' . base64_encode($data->id) . '">Delete</a></li>
                                    </ul>';
                    }

                    $return .= '</div>';
                    return $return;
                })
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('state.index');
    }
        
        /** create */
        public function create(Request $request){
            return view('state.create');
        }

    /** create */

    /** insert */
        public function insert(Request $request){
            if($request->ajax()){
                return true;
            }
        
            
            $crud = [
                'name' => ucfirst($request->name),
                'status' => 'active',
                'created_at' => now(),
                'updated_at' => now()
            ];
        
            DB::beginTransaction();
            try {
                // Use create() instead of insertGetId() if using Eloquent
                $last_id = State::create($crud);
                
                if ($last_id) {
                    DB::commit();
                    return redirect()->route('state')->with('success', 'Record inserted successfully');
                } else {
                    DB::rollback();
                    return redirect()->back()->with('error', 'Failed to insert record')->withInput();
                }
            } catch (\Throwable $th) {
                DB::rollback();
                // \Log::error('Insert Error: ' . $th->getMessage()); // Logs the error
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
        }
    /** insert */

    /** view */
        public function view(Request $request){
            $id = base64_decode($request->id);
            $data = State::where(['id' => $id])->first();
            return view('state.view')->with(['data' => $data]);
        }
    /** view */

    /** edit */
        public function edit(Request $request)
            {
                $id = base64_decode($request->id);
                $data = State::where(['id' => $id])->first();
                return view('state.edit')->with(['data' => $data]);
            } 
    /** edit */

    /** update */
        public function update(Request $request){
            if($request->ajax()){
                return true;
            }
        
            // Validate request
            $request->validate([
                'id' => 'required|exists:common_state,id',
                'name' => 'required|string|max:255',
            ]);
        
            // Prepare data (without `updated_by`)
            $crud = [
                'name' => ucfirst($request->name),
                'updated_at' => now(),
            ];
        
            DB::beginTransaction();
            try {
                // Update the record
                $update = State::where('id', $request->id)->update($crud);
        
                if ($update) {
                    DB::commit();
                    return redirect()->route('state')->with('success', 'Record updated successfully');
                } else {
                    DB::rollback();
                    return redirect()->back()->with('error', 'Failed to update record')->withInput();
                }
            } catch (\Throwable $th) {
                DB::rollback();
                \Log::error('Update Error: ' . $th->getMessage()); // Log the error
                return redirect()->back()->with('error', 'Something went wrong, please try again later')->withInput();
            }
        }

    /** update */
    /** change-status */
        public function change_status(Request $request){
            if (!$request->ajax()) {
                return response()->json(['code' => 400, 'message' => 'Invalid Request']);
            }
    
            $id = base64_decode($request->id);
            $data = State::where('id', $id)->first();
    
            if ($data) {
                $update = State::where('id', $id)->update([
                    'status' => $request->status,
                    'updated_at' => now()
                ]);
    
                return response()->json([
                    'code' => $update ? 200 : 201,
                    'new_status' => $request->status
                ]);
            }
    
            return response()->json(['code' => 201]);
        }
        
        public function export(Request $request){
            if(isset($request->slug) && $request->slug != null){
                $slug = $request->slug;
            }else{
                $slug = 'all';
            }

            $name = 'State'.Date('YmdHis').'.xlsx';

            try {
                return Excel::download(new ExportState($slug), $name);
            }catch(\Exception $e){
                return redirect()->back()->with('error' ,$e->getMessage());
            }
        }
        
        /** Import */
        public function import(Request $request){
               
            if(Excel::import(new ImportState, $request->file('file')->store('file'))){
                return redirect()->route('state')->with('sucess' ,'File Imported Sucessfully');
            }else{
                return redirect()->route('state')->with('error' ,'Faild To Import File!');
            }
        }
        /** Import */
    }
