<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\Doctor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function index()
    {
        $doctor = Doctor::with('user','activeSubscription.plan')->find(session('doctor_id'));
        return view('doctor.profile.index', compact('doctor'));
    }

    public function update(Request $request)
    {
        $doctor = Doctor::with('user')->find(session('doctor_id'));

        $data = $request->validate([
            'clinic_name'           => 'nullable|string|max:100',
            'clinic_address'        => 'nullable|string|max:500',
            'latitude'              => 'nullable|numeric|between:-90,90',
            'longitude'             => 'nullable|numeric|between:-180,180',
            'city'                  => 'nullable|string|max:50',
            'bio'                   => 'nullable|string|max:1000',
            'phone'                 => 'nullable|string|max:20',
            'website'               => 'nullable|string|max:100',
            'prescription_header'   => 'nullable|string|max:200',
            'prescription_footer'   => 'nullable|string|max:200',
            'consultation_fee'      => 'nullable|numeric|min:0',
            'max_daily_patients'    => 'nullable|integer|min:1|max:500',
            'appointment_duration'  => 'nullable|integer|min:5|max:120',
            'logo'                  => 'nullable|image|max:2048',
            'signature'             => 'nullable|image|max:1024',
            'new_password'          => 'nullable|string|min:8|confirmed',
        ]);

        // رفع الشعار
        if ($request->hasFile('logo')) {
            if ($doctor->logo) Storage::disk('public')->delete($doctor->logo);
            $data['logo'] = $request->file('logo')->store('doctors/logos', 'public');
        }

        // رفع التوقيع
        if ($request->hasFile('signature')) {
            if ($doctor->signature) Storage::disk('public')->delete($doctor->signature);
            $data['signature'] = $request->file('signature')->store('doctors/signatures', 'public');
        }

        $doctor->update(\Illuminate\Support\Arr::except(
            $data, ['new_password', 'new_password_confirmation']
        ));

        if (!empty($data['phone'])) {
            $doctor->user->update(['phone' => $data['phone']]);
        }

        if (!empty($data['new_password'])) {
            $doctor->user->update(['password' => Hash::make($data['new_password'])]);
        }

        return back()->with('success', 'تم تحديث الملف الشخصي بنجاح');
    }
}
