<?php

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\Controller;
use App\Models\Secretary;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SecretaryController extends Controller
{
    public function index()
    {
        $doctorId   = session('doctor_id');
        $secretaries = Secretary::with('user')
            ->where('doctor_id', $doctorId)
            ->latest()->get();

        return view('doctor.secretaries.index', compact('secretaries'));
    }

    public function store(Request $request)
    {
        $doctorId = session('doctor_id');

        if (! $doctorId) {
            return back()->with('error', 'تعذر تحديد الطبيب الحالي، أعد تسجيل الدخول');
        }

        $data = $request->validate([
            'name'  => 'required|string|max:100',
            'email' => 'nullable|email|unique:users,email',
            'phone' => 'required|string|unique:users,phone',
        ]);

        $email = ! empty($data['email']) ? $data['email'] : null;

        DB::beginTransaction();
        try {
            $user = User::create([
                'name'      => $data['name'],
                'email'     => $email,
                'phone'     => $data['phone'],
                'password'  => User::randomPasswordHash(),
                'role'      => 'secretary',
                'doctor_id' => $doctorId,
                'is_active' => true,
            ]);

            Secretary::create([
                'doctor_id' => $doctorId,
                'user_id'   => $user->id,
                'is_active' => true,
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            return back()->with('error', 'حدث خطأ: ' . $e->getMessage())->withInput();
        }

        return back()->with('success', 'تم إضافة السكرتير ' . $data['name'] . ' بنجاح — يمكنه الدخول برقم هاتفه من الصفحة الرئيسية');
    }

    public function toggle($id)
    {
        $sec = Secretary::where('doctor_id', session('doctor_id'))->findOrFail($id);
        $sec->update(['is_active' => ! $sec->is_active]);
        $sec->user->update(['is_active' => $sec->is_active]);

        return back()->with('success', $sec->is_active ? 'تم تفعيل السكرتير' : 'تم إيقاف السكرتير');
    }

    public function destroy($id)
    {
        $sec = Secretary::where('doctor_id', session('doctor_id'))->with('user')->findOrFail($id);
        $sec->user->delete();
        $sec->delete();

        return back()->with('success', 'تم حذف حساب السكرتير');
    }
}
