<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Campaign;
use App\Models\Guest;
use App\Models\Venue;
use App\Models\GuestVisit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AdminController extends Controller
{
    public function getKpis()
    {
        $today = now()->toDateString();

        return response()->json([
            'today_checkins' => GuestVisit::whereDate('visit_date', $today)->count(),
            'active_members' => Guest::whereHas('visits', function($q) use ($today) {
                $q->whereDate('visit_date', '>=', now()->subDays(30));
            })->count(),
            'total_guests' => Guest::count(),
            'total_visits' => GuestVisit::count(),
            'revenue_today' => GuestVisit::whereDate('visit_date', $today)->sum('spend_amount'),
        ]);
    }

    public function getCharts()
    {
        $visitsByVenue = GuestVisit::select('venues.name', DB::raw('count(*) as visits'))
            ->join('venues', 'guest_visits.venue_id', '=', 'venues.id')
            ->groupBy('venues.id', 'venues.name')
            ->get();

        $tierDistribution = Guest::select('loyalty_tiers.name', DB::raw('count(*) as count'))
            ->join('loyalty_tiers', 'guests.tier_id', '=', 'loyalty_tiers.id')
            ->groupBy('loyalty_tiers.id', 'loyalty_tiers.name')
            ->get();

        return response()->json([
            'visits_by_venue' => $visitsByVenue,
            'tier_distribution' => $tierDistribution,
        ]);
    }

    public function createCampaign(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'segment_rules' => 'required|array',
            'offer_text' => 'required|string',
            'voucher_id' => 'required|exists:vouchers,id',
        ]);

        $campaign = Campaign::create($request->all());

        return response()->json($campaign, 201);
    }

    public function getVenues()
    {
        return response()->json(Venue::all());
    }
}
