<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use Illuminate\Http\Request;

class DirectoryController extends BaseApiController
{
    /**
     * Get paginated list of members in the same association
     */
    public function members(Request $request)
    {
        $associationId = $request->input('association_id', $request->user()->associations()->first()?->id);
        
        if (!$associationId) {
            return $this->error('Association ID required', null, 400);
        }

        // Verify user belongs to this association
        if (!$request->user()->associations()->where('associations.id', $associationId)->exists()) {
            return $this->error('Unauthorized access to this association', null, 403);
        }

        $search = $request->input('search');
        $perPage = $request->input('per_page', 20);
        $sortBy = $request->input('sort_by', 'firstname');
        $sortOrder = $request->input('sort_order', 'asc');

        $query = User::whereHas('associations', function ($q) use ($associationId) {
            $q->where('association_user.association_id', $associationId);
        })
        ->with(['associations', 'workProfile:id,user_id,category,job_title,availability_status'])
        ->when($search, function ($q) use ($search) {
            $q->where(function ($query) use ($search) {
                $query->where('firstname', 'like', "%{$search}%")
                    ->orWhere('surname', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        })
        ->orderBy($sortBy, $sortOrder);

        return $this->paginated($query, $perPage);
    }

    /**
     * Get detailed information about a specific member
     */
    public function memberDetails(Request $request, $id)
    {
        $associationId = $request->input('association_id', $request->user()->associations()->first()?->id);

        // Verify user belongs to this association
        if (!$request->user()->associations()->where('associations.id', $associationId)->exists()) {
            return $this->error('Unauthorized access', null, 403);
        }

        $member = User::whereHas('associations', function ($q) use ($associationId) {
            $q->where('association_user.association_id', $associationId);
        })
        ->with(['associations', 'profileFieldValues.profileField', 'workProfile'])
        ->find($id);

        if (!$member) {
            return $this->error('Member not found', null, 404);
        }

        return $this->success($member, 'Member details retrieved successfully');
    }
}
