<?php

namespace App\Http\Controllers;

use App\Models\TicketCenter;
use App\Models\User;
use App\Traits\AuditLogTrait;
use Illuminate\Http\Request;

class TicketCenterController extends Controller
{
    use AuditLogTrait;
    public function index()
    {
        $ticketCenters = TicketCenter::getCentersWithStaff();
        return view('admin.ticket-centers.index', compact('ticketCenters'));
    }

    public function create()
    {
        $availableStaff = TicketCenter::getAvailableStaff();
        return view('admin.ticket-centers.create', compact('availableStaff'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'location' => 'required|string|max:100',
            'staff_user_id' => 'required|exists:users,id',
        ]);

        // Check if staff is already assigned to another center
        if (TicketCenter::isUserAssigned($validated['staff_user_id'])) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['staff_user_id' => 'This staff member is already assigned to another ticket center.']);
        }

        $ticketCenter = TicketCenter::create($validated);

        $this->logCreate($ticketCenter, "Created new ticket center: {$ticketCenter->name} at {$ticketCenter->location}");

        return redirect()->route('admin.ticket-centers.index')
            ->with('success', 'Ticket center created successfully.');
    }

    public function show(TicketCenter $ticketCenter)
    {
        $ticketCenter->load('staff');
        return view('admin.ticket-centers.show', compact('ticketCenter'));
    }

    public function edit(TicketCenter $ticketCenter)
    {
        $availableStaff = TicketCenter::getAvailableStaff($ticketCenter->center_id);
        $currentStaff = $ticketCenter->staff;

        // Include current staff in the list if they exist
        if ($currentStaff && !$availableStaff->contains('id', $currentStaff->id)) {
            $availableStaff->push($currentStaff);
        }

        return view('admin.ticket-centers.edit', compact('ticketCenter', 'availableStaff'));
    }

    public function update(Request $request, TicketCenter $ticketCenter)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'location' => 'required|string|max:100',
            'staff_user_id' => 'required|exists:users,id',
        ]);

        // Check if staff is already assigned to another center (excluding current center)
        if (TicketCenter::isUserAssigned($validated['staff_user_id'], $ticketCenter->center_id)) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['staff_user_id' => 'This staff member is already assigned to another ticket center.']);
        }

        $oldValues = $ticketCenter->toArray();
        $ticketCenter->update($validated);

        $this->logUpdate($ticketCenter, $oldValues, "Updated ticket center: {$ticketCenter->name}");

        return redirect()->route('admin.ticket-centers.index')
            ->with('success', 'Ticket center updated successfully.');
    }

    public function destroy(TicketCenter $ticketCenter)
    {
        $this->logDelete($ticketCenter, "Deleted ticket center: {$ticketCenter->name}");

        $ticketCenter->delete();

        return redirect()->route('admin.ticket-centers.index')
            ->with('success', 'Ticket center deleted successfully.');
    }

    /**
     * Get available staff via AJAX
     */
    public function getAvailableStaff(Request $request)
    {
        $excludeCenterId = $request->get('exclude_center_id');
        $availableStaff = TicketCenter::getAvailableStaff($excludeCenterId);

        return response()->json($availableStaff);
    }
}
