<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Priority;
use Illuminate\Http\Request;

class PriorityController extends Controller
{
    public function list()
    {
        $pageTitle  = 'Priority List';
        $priorities = Priority::withCount('pendingSupportTickets')->with('admin')->orderBy('id', 'desc')->get();
        return view('admin.setting.ticket_general_setting.priority', compact('pageTitle', 'priorities'));
    }

    public function save(Request $request, $id = 0)
    {
        $request->validate([
            'name'  => 'required|string',
            'color' => 'required|regex:/^[a-f0-9]{6}$/i',
        ]);

        if ($id) {
            $priority = Priority::findOrFail($id);
            $message  = 'Priority updated successfully';
        } else {
            $priority           = new Priority();
            $priority->admin_id = auth('admin')->id();
            $message            = 'Priority added successfully';
        }

        $priority->name            = $request->name;
        $priority->color           = $request->color;
        $priority->converted_color = hexToHsl($request->color);
        $priority->save();

        $notify[] = ['success', $message];
        return back()->withNotify($notify);
    }

    public function status($id)
    {
        $priority = Priority::find($id);
        if (!$priority) {
            return response()->json([
                'status'  => 'error',
                'message' => 'No priority found',
            ]);
        }

        $priority->status = !$priority->status;
        $priority->save();

        $message = $priority->status ? 'Priority enabled successfully' : 'Priority disabled successfully';
        return response()->json([
            'status'   => 'success',
            'message'  => $message,
            'priority' => $priority,
        ]);
    }
}
