<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class SupportController extends Controller
{
    public function index()
    {
        $tickets = [];

        return view('admin.support.index', compact('tickets'));

    }

    public function getSupportList(Request $request){
        $sqlBuilder = SupportTicket::select([
            'support_tickets.id',
            'support_tickets.subject',
            'support_tickets.description',
            'support_tickets.status',
            'support_tickets.created_at',
            'users.name as user_name',
        ])->join('users', 'support_tickets.user_id', '=', 'users.id')
        ->orderBy('support_tickets.created_at', 'desc');

        return DataTables::of($sqlBuilder)
        ->filter(function ($query) use ($request) {
            if ($request->has('search') && !empty($request->search['value'])) {
                $query->where('support_tickets.subject', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('support_tickets.description', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('users.name', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('users.last_name', 'ilike', "%" . $request->search['value'] . "%");
            }
        })
        ->editColumn('created_at', function ($data) {
            return $data->created_at->format('d/m/y H:i A');
        })
            ->editColumn('status', function ($data) {
            return '<div class="status">
                        <div class="form-check form-switch ">
                            <input class="form-check-input status-checkbox" type="checkbox" role="switch" id="SwitchCheck4" data-url="'. route('admin.support.status', ['id' => $data->id]) .'" data-id="'.$data->id.'" '.(!empty($data->status) && $data->status == 1 ? 'checked' : '').' />
                        </div>
                    </div>';
            })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . route('admin.support.show', ['id' => $data->id]) . '">Details</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.support.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
            return $html;
            })
            ->rawColumns(['created_at','status','action'])
            ->make(true);
    }

    public function show($id)
    {
        $ticket = SupportTicket::findOrFail($id);
        return view('admin.support.details', compact('ticket'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $emirate = SupportTicket::findOrFail($id);           
            $emirate->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Ticket deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Ticket not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the company.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id) {
        $ticket = SupportTicket::find($id);

        if (!$ticket) {
            return response()->json([
                'status' => 'error',
                'message' => 'Ticket not found.'
            ], 404);
        }
    
        $ticket->status = $request->status;
        $ticket->save();
    
        return response()->json([
            'status' => 'success',
            'message' => 'Ticket status updated successfully.'
        ]);
    }
}
