<?php

namespace App\Http\Controllers\PartnerApp;

use App\Http\Controllers\Controller;
use App\Models\PartnerTeamMember;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class TeamController extends Controller
{
    private function ensureProfile()
    {
        $user = Auth::user();
        $profile = \App\Models\PartnerProfile::firstOrCreate(
            ['user_id' => $user->id],
            ['display_name' => $user->name, 'is_available' => true]
        );
        return $profile;
    }

    public function index()
    {
        $profile = $this->ensureProfile();
        $members = $profile->teamMembers()->orderByDesc('is_active')->orderBy('name')->get();
        return view('partnerapp.team', compact('profile', 'members'));
    }

    public function store(Request $request)
    {
        $profile = $this->ensureProfile();
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'phone' => ['required', 'string', 'max:20'],
            'email' => ['nullable', 'email'],
            'role' => ['nullable', 'string', 'max:60'],
            'photo' => ['nullable', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ]);

        $photo = null;
        if ($request->hasFile('photo')) {
            $photo = $request->file('photo')->store('team/' . $profile->user_id, 'public');
        }

        $loginUser = null;
        if (!empty($data['email'])) {
            $loginUser = \App\Models\User::firstOrCreate(
                ['email' => $data['email']],
                [
                    'name' => $data['name'],
                    'phone' => $data['phone'],
                    'password' => Hash::make(Str::random(12)),
                    'role' => 'team_member',
                ]
            );
        }

        PartnerTeamMember::create([
            'partner_id' => $profile->id,
            'user_id' => $loginUser?->id,
            'name' => $data['name'],
            'phone' => $data['phone'],
            'email' => $data['email'] ?? null,
            'role' => $data['role'] ?? 'Helper',
            'photo' => $photo,
            'is_active' => true,
        ]);

        return back()->with('success', 'Team member added. They can now be assigned visits.');
    }

    public function toggle(PartnerTeamMember $member)
    {
        $profile = $this->ensureProfile();
        abort_unless($member->partner_id === $profile->id, 403);
        $member->update(['is_active' => !$member->is_active]);
        return back()->with('success', $member->is_active ? 'Team member reactivated.' : 'Team member disabled.');
    }

    public function destroy(PartnerTeamMember $member)
    {
        $profile = $this->ensureProfile();
        abort_unless($member->partner_id === $profile->id, 403);
        $member->delete();
        return back()->with('success', 'Team member removed.');
    }
}
