<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\TeamMember;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class TeamMemberController extends Controller
{
    public function index(Request $request)
    {
        $query = TeamMember::query()
            ->orderBy('sort_order')
            ->latest();

        if ($request->filled('status')) {
            if ($request->query('status') === 'active') {
                $query->active();
            }

            if ($request->query('status') === 'inactive') {
                $query->where('is_active', false);
            }
        }

        if ($request->filled('department')) {
            $query->where('department', $request->query('department'));
        }

        if ($request->boolean('featured')) {
            $query->featured();
        }

        if ($request->filled('search')) {
            $search = $request->query('search');

            $query->where(function ($q) use ($search) {
                $q->where('full_name', 'like', "%{$search}%")
                    ->orWhere('title', 'like', "%{$search}%")
                    ->orWhere('department', 'like', "%{$search}%")
                    ->orWhere('bio', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $members = $query->get()
            ->map(fn ($member) => $this->toArray($member))
            ->values();

        return response()->json([
            'data' => $members,
        ]);
    }

    public function store(Request $request)
    {
        $data = $this->validateData($request);

        $member = TeamMember::create([
            'full_name' => $data['full_name'],
            'slug' => $data['slug'] ?? $this->uniqueSlug($data['full_name']),

            'title' => $data['title'] ?? null,
            'department' => $data['department'] ?? null,
            'bio' => $data['bio'] ?? null,

            'image' => $data['image'] ?? null,

            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'whatsapp_phone' => $data['whatsapp_phone'] ?? null,

            'linkedin_url' => $data['linkedin_url'] ?? null,
            'instagram_url' => $data['instagram_url'] ?? null,

            'sort_order' => $data['sort_order'] ?? 0,
            'is_active' => $data['is_active'] ?? true,
            'is_featured' => $data['is_featured'] ?? false,
        ]);

        return response()->json([
            'data' => $this->toArray($member),
        ], 201);
    }

    public function show(TeamMember $member)
    {
        return response()->json([
            'data' => $this->toArray($member),
        ]);
    }

    public function update(Request $request, TeamMember $member)
    {
        $data = $this->validateData($request, $member->id);

        $member->update([
            'full_name' => $data['full_name'] ?? $member->full_name,
            'slug' => $data['slug'] ?? $member->slug,

            'title' => array_key_exists('title', $data) ? $data['title'] : $member->title,
            'department' => array_key_exists('department', $data) ? $data['department'] : $member->department,
            'bio' => array_key_exists('bio', $data) ? $data['bio'] : $member->bio,

            'image' => array_key_exists('image', $data) ? $data['image'] : $member->image,

            'email' => array_key_exists('email', $data) ? $data['email'] : $member->email,
            'phone' => array_key_exists('phone', $data) ? $data['phone'] : $member->phone,
            'whatsapp_phone' => array_key_exists('whatsapp_phone', $data) ? $data['whatsapp_phone'] : $member->whatsapp_phone,

            'linkedin_url' => array_key_exists('linkedin_url', $data) ? $data['linkedin_url'] : $member->linkedin_url,
            'instagram_url' => array_key_exists('instagram_url', $data) ? $data['instagram_url'] : $member->instagram_url,

            'sort_order' => $data['sort_order'] ?? $member->sort_order,
            'is_active' => $data['is_active'] ?? $member->is_active,
            'is_featured' => $data['is_featured'] ?? $member->is_featured,
        ]);

        return response()->json([
            'data' => $this->toArray($member->fresh()),
        ]);
    }

    public function destroy(TeamMember $member)
    {
        $member->delete();

        return response()->json([
            'message' => 'Ekip üyesi silindi.',
        ]);
    }

    public function activate(TeamMember $member)
    {
        $member->update([
            'is_active' => true,
        ]);

        return response()->json([
            'data' => $this->toArray($member->fresh()),
        ]);
    }

    public function deactivate(TeamMember $member)
    {
        $member->update([
            'is_active' => false,
        ]);

        return response()->json([
            'data' => $this->toArray($member->fresh()),
        ]);
    }

    private function validateData(Request $request, ?int $ignoreId = null): array
    {
        return $request->validate([
            'full_name' => [$ignoreId ? 'sometimes' : 'required', 'string', 'max:255'],

            'slug' => [
                'nullable',
                'string',
                'max:255',
                Rule::unique('team_members', 'slug')->ignore($ignoreId),
            ],

            'title' => ['nullable', 'string', 'max:255'],
            'department' => ['nullable', 'string', 'max:255'],
            'bio' => ['nullable', 'string'],

            'image' => ['nullable', 'string', 'max:1000'],

            'email' => ['nullable', 'email', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'whatsapp_phone' => ['nullable', 'string', 'max:50'],

            'linkedin_url' => ['nullable', 'string', 'max:1000'],
            'instagram_url' => ['nullable', 'string', 'max:1000'],

            'sort_order' => ['nullable', 'integer'],
            'is_active' => ['nullable', 'boolean'],
            'is_featured' => ['nullable', 'boolean'],
        ]);
    }

    private function toArray(TeamMember $member): array
    {
        return [
            'id' => $member->id,

            'full_name' => $member->full_name,
            'slug' => $member->slug,

            'title' => $member->title,
            'department' => $member->department,
            'bio' => $member->bio,

            'image' => $member->image,

            'email' => $member->email,
            'phone' => $member->phone,
            'whatsapp_phone' => $member->whatsapp_phone,

            'linkedin_url' => $member->linkedin_url,
            'instagram_url' => $member->instagram_url,

            'sort_order' => $member->sort_order,
            'is_active' => $member->is_active,
            'is_featured' => $member->is_featured,

            'created_at' => $member->created_at?->toISOString(),
            'updated_at' => $member->updated_at?->toISOString(),
        ];
    }

    private function uniqueSlug(string $fullName): string
    {
        $base = Str::slug($fullName) ?: 'team-member';
        $slug = $base;
        $i = 1;

        while (TeamMember::where('slug', $slug)->exists()) {
            $slug = "{$base}-{$i}";
            $i++;
        }

        return $slug;
    }
}