<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Outlet;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class OutletController extends Controller
{
    /**
     * Display a listing of the outlets.
     */
    public function index(Request $request): Response
    {
        $search = $request->input('search');

        $outlets = Outlet::withCount([
            'users' => function ($query) {
                $query->role(['Kasir', 'Kitchen']);
            },
            'transactions'
        ])
            ->when($search, function ($query, $search) {
                $query->where('name', 'like', "%{$search}%")
                      ->orWhere('location', 'like', "%{$search}%");
            })
            ->latest()
            ->paginate(10)
            ->withQueryString();

        // Get cashiers and kitchen staff (users with Role 'Kasir' or 'Kitchen') to map and assign
        $availableUsers = User::role(['Kasir', 'Kitchen'])
            ->with(['outlet:id,name', 'roles:name'])
            ->select('id', 'name', 'email', 'outlet_id')
            ->get();

        return Inertia::render('CafePOS/Outlets/Index', [
            'outlets' => $outlets,
            'availableUsers' => $availableUsers,
            'filters' => [
                'search' => $search,
            ],
        ]);
    }

    /**
     * Store a newly created outlet in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'location' => ['nullable', 'string'],
            'description' => ['nullable', 'string'],
            'assigned_users' => ['nullable', 'array'],
            'assigned_users.*' => ['integer', 'exists:users,id'],
        ]);

        $outlet = Outlet::create([
            'name' => $request->name,
            'location' => $request->location,
            'description' => $request->description,
        ]);

        if ($request->has('assigned_users')) {
            // Update assigned users
            User::whereIn('id', $request->assigned_users)->update(['outlet_id' => $outlet->id]);
        }

        activity()
            ->performedOn($outlet)
            ->causedBy($request->user())
            ->log("Created outlet: {$outlet->name}");

        return redirect()->back()->with('success', 'Outlet created successfully.');
    }

    /**
     * Update the specified outlet in storage.
     */
    public function update(Request $request, Outlet $outlet): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'location' => ['nullable', 'string'],
            'description' => ['nullable', 'string'],
            'assigned_users' => ['nullable', 'array'],
            'assigned_users.*' => ['integer', 'exists:users,id'],
        ]);

        $outlet->update([
            'name' => $request->name,
            'location' => $request->location,
            'description' => $request->description,
        ]);

        // Unassign users who were previously assigned to this outlet but are not in the new list
        User::where('outlet_id', $outlet->id)
            ->when($request->has('assigned_users'), function ($query) use ($request) {
                $query->whereNotIn('id', $request->assigned_users);
            })
            ->update(['outlet_id' => null]);

        // Assign new users
        if ($request->has('assigned_users') && !empty($request->assigned_users)) {
            User::whereIn('id', $request->assigned_users)->update(['outlet_id' => $outlet->id]);
        }

        activity()
            ->performedOn($outlet)
            ->causedBy($request->user())
            ->log("Updated outlet: {$outlet->name}");

        return redirect()->back()->with('success', 'Outlet updated successfully.');
    }

    /**
     * Remove the specified outlet from storage.
     */
    public function destroy(Request $request, Outlet $outlet): RedirectResponse
    {
        $name = $outlet->name;

        // Perform activity log before delete
        activity()
            ->performedOn($outlet)
            ->causedBy($request->user())
            ->log("Deleted outlet: {$name}");

        $outlet->delete();

        return redirect()->back()->with('success', 'Outlet deleted successfully.');
    }
}
