<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePatientRequest;
use App\Http\Requests\UpdatePatientRequest;
use App\Http\Resources\PatientResource;
use App\Http\Resources\PatientProfileResource;
use App\Models\Patient;
use Illuminate\Http\Request;

class PatientController extends Controller
{
    public function index(Request $request)
    {
        $query = Patient::query();

        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('email', 'like', "%{$search}%")
                  ->orWhere('phone', 'like', "%{$search}%")
                  ->orWhere('patient_code', 'like', "%{$search}%");
            });
        }

        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        $patients = $query->orderBy('created_at', 'desc')->paginate($request->per_page ?? 20);

        return PatientResource::collection($patients);
    }

    public function store(StorePatientRequest $request)
    {
        $data = $request->validated();
        $data['created_by'] = auth()->id();
        
        // Generate patient code
        $lastId = Patient::max('id') ?? 0;
        $data['patient_code'] = 'P' . str_pad($lastId + 1, 6, '0', STR_PAD_LEFT);

        $patient = Patient::create($data);

        return new PatientResource($patient);
    }

    public function show(Patient $patient)
    {
        return new PatientResource($patient);
    }

    public function profile(Patient $patient)
    {
        return new PatientProfileResource($patient);
    }

    public function update(UpdatePatientRequest $request, Patient $patient)
    {
        $patient->update($request->validated());
        return new PatientResource($patient);
    }

    public function destroy(Patient $patient)
    {
        $patient->delete();
        return response()->json(['message' => 'Patient deleted successfully']);
    }
}
