<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Mandabam;
use App\Models\Booking;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    public function dashboard()
    {
        $totalUsers = User::count();
        $totalOwners = User::where('role', 'owner')->count();
        $totalCustomers = User::where('role', 'customer')->count();

        $totalHalls = Mandabam::count();
        $approvedHalls = Mandabam::where('status', 'approved')->count();
        $pendingHalls = Mandabam::where('status', 'pending')->count();

        $totalBookings = Booking::count();
        $confirmedBookings = Booking::where('status', 'confirmed')->count();

        $totalRevenue = Booking::where('status', 'confirmed')
            ->where('payment_status', 'paid')
            ->sum('advance_amount');

        return response()->json([
            'success' => true,
            'data' => [
                'totalUsers' => $totalUsers,
                'totalOwners' => $totalOwners,
                'totalCustomers' => $totalCustomers,
                'totalHalls' => $totalHalls,
                'approvedHalls' => $approvedHalls,
                'pendingHalls' => $pendingHalls,
                'totalBookings' => $totalBookings,
                'confirmedBookings' => $confirmedBookings,
                'totalRevenue' => $totalRevenue
            ]
        ]);
    }

    public function pendingHalls()
    {
        $halls = Mandabam::where('status', 'pending')
            ->with('owner:id,name,email')
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'data' => $halls
        ]);
    }


    public function approveHall($id)
    {
        $hall = Mandabam::findOrFail($id);

        $hall->update([
            'status' => 'approved'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Hall approved successfully'
        ]);
    }

    public function rejectHall($id)
    {
        $hall = Mandabam::findOrFail($id);

        $hall->update([
            'status' => 'rejected'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Hall rejected successfully'
        ]);
    }

    public function users()
    {
        $users = User::select('id', 'name', 'email', 'role', 'created_at')
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'data' => $users
        ]);
    }

    public function allBookings()
    {
        $bookings = Booking::with([
                'user:id,name,email',
                'mandabam:id,name,location'
            ])
            ->latest()
            ->get();

        return response()->json([
            'success' => true,
            'data' => $bookings
        ]);
    }
}