<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rules\Password;
use Inertia\Inertia;
use App\Models\ComplianceLog;
use App\Models\ProgressPhoto;

/**
 * ProfileController
 * Handles client profile management with biometric data
 */
class ProfileController extends Controller
{
    /**
     * Display the client's profile page with biometric data
     */
    public function index()
    {
        $user = auth()->user();
        $client = $user->clientProfile ?? $user->client;
        
        if (!$client) {
            return Inertia::render('Client/Profile/Index', [
                'no_profile' => true,
                'user' => $user->only(['id', 'name', 'email', 'avatar']),
            ]);
        }
        
        // Calculate biometric data using Client model methods
        $bmr = $client->calculateBmr();
        $tdee = $client->calculateTdee();
        $bmi = $client->calculateBmi();
        $macros = $client->calculateMacros();
        
        // Calculate ideal weight (based on BMI of 22)
        $idealWeight = null;
        if ($client->height) {
            $heightM = $client->height / 100;
            $idealWeight = round(22 * ($heightM * $heightM), 1);
        }
        
        // Calculate calorie adjustment based on objective
        $targetCalories = null;
        $calorieAdjustmentPercent = 0;
        if ($tdee) {
            switch($client->objective) {
                case 'lose':
                    $calorieAdjustmentPercent = -20;
                    $targetCalories = round($tdee * 0.8);
                    break;
                case 'gain':
                    $calorieAdjustmentPercent = 15;
                    $targetCalories = round($tdee * 1.15);
                    break;
                default:
                    $calorieAdjustmentPercent = 0;
                    $targetCalories = round($tdee);
            }
        }
        
        // Get coach info
        $coach = null;
        if ($client->user) {
            $coachUser = $client->user;
            $avatar = $coachUser->avatar;
            $avatarUrl = $avatar 
                ? (str_starts_with($avatar, 'http') || str_starts_with($avatar, '/storage/') ? $avatar : '/storage/' . $avatar)
                : null;
                
            $coach = [
                'id' => $coachUser->id,
                'name' => $coachUser->name,
                'email' => $coachUser->email,
                'avatar' => $avatarUrl,
                'bio' => $coachUser->bio,
                'specializations' => $coachUser->specializations,
                'years_experience' => $coachUser->years_experience,
            ];
        }
        
        // Get stats
        $stats = [
            'workouts_completed' => ComplianceLog::where('client_id', $client->id)
                ->where('resource_type', 'workout')
                ->count(),
            'meals_completed' => ComplianceLog::where('client_id', $client->id)
                ->where('resource_type', 'meal')
                ->count(),
            'photos_count' => ProgressPhoto::where('client_id', $client->id)->count(),
            'member_since' => $client->created_at?->format('d/m/Y'),
        ];
        
        // Get recent weight history
        $weightHistory = ProgressPhoto::where('client_id', $client->id)
            ->whereNotNull('weight')
            ->orderBy('date', 'desc')
            ->limit(10)
            ->get(['weight', 'date'])
            ->map(fn($p) => [
                'weight' => $p->weight,
                'date' => $p->date->format('d/m'),
            ])
            ->reverse()
            ->values();
        
        return Inertia::render('Client/Profile/Index', [
            'client' => $client,
            'user' => $user->only(['id', 'name', 'email', 'avatar']),
            'coach' => $coach,
            'biometrics' => [
                'bmi' => $bmi,
                'bmr' => $bmr,
                'tdee' => $tdee,
                'ideal_weight' => $idealWeight,
                'macros' => $macros,
                'target_calories' => $targetCalories,
                'calorie_adjustment_percent' => $calorieAdjustmentPercent,
            ],
            'stats' => $stats,
            'weight_history' => $weightHistory,
        ]);
    }
    
    /**
     * Update the client's profile information
     */
    public function update(Request $request)
    {
        $user = auth()->user();
        
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255|unique:users,email,' . $user->id,
            'phone' => 'nullable|string|max:20',
        ]);
        
        $user->update([
            'name' => $validated['name'],
            'email' => $validated['email'],
        ]);
        
        if ($user->client && isset($validated['phone'])) {
            $user->client->update(['phone' => $validated['phone']]);
        }
        
        return back()->with('success', 'Perfil actualizado correctamente');
    }
    
    /**
     * Update the client's password
     */
    public function updatePassword(Request $request)
    {
        $validated = $request->validate([
            'current_password' => ['required', 'current_password'],
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);
        
        $request->user()->update([
            'password' => Hash::make($validated['password']),
        ]);
        
        return back()->with('success', 'Contraseña actualizada correctamente');
    }

    /**
     * Update the client's avatar
     */
    public function updateAvatar(Request $request)
    {
        $request->validate([
            'avatar' => ['required', 'image', 'max:10240'],
        ]);

        $user = $request->user();

        // Delete old avatar if exists
        if ($user->avatar && str_starts_with($user->avatar, '/storage/')) {
            $oldPath = str_replace('/storage/', '', $user->avatar);
            Storage::disk('public')->delete($oldPath);
        }

        // Store new avatar
        if ($request->hasFile('avatar') && $request->file('avatar')->isValid()) {
            $path = $request->file('avatar')->store('avatars/' . $user->id, 'public');
            $user->update(['avatar' => '/storage/' . $path]);
        }

        return back()->with('success', 'Foto de perfil actualizada');
    }
}
