<?php

namespace App\Http\Controllers\Patients;

use App\Http\Controllers\Controller;
use App\Models\Patient;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class PatientController extends Controller
{
    // Apply auth middleware to all methods
    public function __construct()
    {
        $this->middleware('auth');
    }
    
    // List all patients (PatientListView)
   public function index(Request $request)
{
    $query = Patient::query();
    
    // Search
    if ($request->has('search')) {
        $search = $request->search;
        $query->where(function($q) use ($search) {
            $q->where('first_name', 'like', "%{$search}%")
              ->orWhere('last_name', 'like', "%{$search}%")
              ->orWhere('national_code', 'like', "%{$search}%")
              ->orWhere('phone_number', 'like', "%{$search}%");
        });
    }
    
    // Filter by gender
    if ($request->has('gender')) {
        $query->where('sex', $request->gender);
    }
    
    // Filter by age group
    if ($request->has('age_group')) {
        switch($request->age_group) {
            case 'child':
                $query->where('age', '<', 18);
                break;
            case 'adult':
                $query->whereBetween('age', [18, 65]);
                break;
            case 'senior':
                $query->where('age', '>', 65);
                break;
        }
    }
    
    // Sorting
    $sort = $request->get('sort', 'created_at');
    $order = $request->get('order', 'desc');
    $query->orderBy($sort, $order);
    
    // Get statistics
    $totalPatients = Patient::count();
    $maleCount = Patient::where('sex', 'مرد')->count();
    $femaleCount = Patient::where('sex', 'زن')->count();
    $averageAge = Patient::avg('age');
    
    // Get patients with diagnosis counts
    $patients = $query->withCount('diagnoses')
                      ->with(['latestDiagnosis'])
                      ->paginate($request->get('per_page', 20))
                      ->appends($request->query());
    
    return view('patients.index', compact(
        'patients',
        'totalPatients',
        'maleCount',
        'femaleCount',
        'averageAge'
    ));
}
    
    // Show single patient (PatientShowView)

    public function show($id)
{
    $patient = Patient::findOrFail($id);
    
    // Get patient's diagnosis history
    $diagnoses = $patient->diagnoses()->latest()->get();
    
    // Calculate statistics
    $positiveDiagnoses = $diagnoses->where('result', 'positive')->count();
    $negativeDiagnoses = $diagnoses->where('result', 'negative')->count();
    $avgConfidence = $diagnoses->avg('confidence') ?? 0;
    
    return view('patients.detail', compact(
        'patient', 
        'diagnoses',
        'positiveDiagnoses',
        'negativeDiagnoses',
        'avgConfidence'
    ));
}
    
    // Create patient - GET (PatientCreateView.get)
    public function create()
    {
        return view('patients.create');
    }
    
    // Create patient - POST (PatientCreateView.post)
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), Patient::rules(), Patient::validationMessages());
        
        if ($validator->fails()) {
            return redirect()->route('patients.create')
                ->withErrors($validator)
                ->withInput()
                ->with('error', 'لطفا فرم را به درستی پر کنید');
        }
        
        $patient = Patient::create($validator->validated());
        
        return redirect()->route('patients.show', $patient->id)
            ->with('success', 'کاربر با موفقیت اضافه شد');
    }
    
    // Edit patient - GET (PatientEditView.get)
    public function edit($id)
    {
        $patient = Patient::findOrFail($id);
        return view('patients.edit', compact('patient'));
    }
    
    // Edit patient - POST (PatientEditView.post)
    public function update(Request $request, $id)
    {
        $patient = Patient::findOrFail($id);
        
        $validator = Validator::make($request->all(), Patient::rules($id), Patient::validationMessages());
        
        if ($validator->fails()) {
            return redirect()->route('patients.edit', $id)
                ->withErrors($validator)
                ->withInput();
        }
        
        $patient->update($validator->validated());
        
        return redirect()->route('patients.show', $patient->id)
            ->with('success', 'اطلاعات کاربر با موفقیت به‌روزرسانی شد');
    }
    
    // Delete patient (PatientDeleteView)
    public function destroy($id)
    {
        $patient = Patient::findOrFail($id);
        $patient->delete();
        
        return redirect()->route('patients.index')
            ->with('success', 'کاربر حذف شد');
    }
}