<?php

namespace App\Http\Controllers;

use App\Models\AstrologyProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AstrologyProfileController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $astrologyProfile = $user->astrologyProfile;
        return view('astrology-profile', compact('astrologyProfile'));
    }

public function update(Request $request)
{
    $user = Auth::user();

    $validated = $request->validate([
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users,email,' . $user->id,
        // Astrology Fields (Updated to match your schema)
        'dob' => 'nullable|date',
        'tob' => 'nullable',
        'pob' => 'nullable|string|max:255',
        'gender' => 'nullable|string|in:male,female,other',
        // Password...
        'current_password' => 'nullable|required_with:new_password',
        'new_password' => ['nullable', 'confirmed', \Illuminate\Validation\Rules\Password::defaults()],
    ]);

    // 1. Update User Basic Info
    $user->name = $validated['name'];
    $user->email = $validated['email'];

    if ($request->filled('current_password')) {
        if (!\Illuminate\Support\Facades\Hash::check($request->current_password, $user->password)) {
            return back()->withErrors(['current_password' => 'Current password does not match.']);
        }
        $user->password = \Illuminate\Support\Facades\Hash::make($request->new_password);
    }
    $user->save();

    // 2. Update Astrology Profile (Using your column names)
    if ($request->filled('dob')) {
        \App\Models\AstrologyProfile::updateOrCreate(
            ['user_id' => $user->id],
            [
                'full_name' => $user->name, // Syncing with user name
                'dob' => $request->dob,
                'tob' => $request->tob,
                'pob' => $request->pob,
                'gender' => $request->gender,
                // Leaving lat/long/timezone null/default for now
            ]
        );
    }

    return back()->with('success', 'Profile and Kundali details updated successfully.');
}
}
