<?php

namespace App\Http\Controllers\Admin;

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

class AppointmentController extends Controller
{
    public function index()
    {
        return response()->json(Appointment::with('doctor', 'service')->orderBy('appointment_date', 'desc')->get());
    }

    public function getCustomers()
    {
        $customers = Appointment::select(
            'customer_name',
            'customer_mobile',
            DB::raw('COUNT(*) as total_appointments'),
            DB::raw('MAX(appointment_date) as last_visit')
        )
            ->groupBy('customer_mobile', 'customer_name')
            ->orderBy('last_visit', 'desc')
            ->get();

        return response()->json($customers);
    }

    public function updateStatus(Request $request, $id)
    {
        $appointment = Appointment::findOrFail($id);
        $appointment->update(['status' => $request->status]);
        return response()->json($appointment);
    }

    public function destroy($id)
    {
        Appointment::destroy($id);
        return response()->json(['message' => 'Appointment deleted']);
    }
}
