<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\Rental;
use App\Models\Locker;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    /**
     * GET /api/reports/revenue
     */
    public function revenue(Request $request)
    {
        $from = $request->get('from', now()->startOfMonth()->toDateString());
        $to   = $request->get('to',   now()->toDateString());

        $summary = Payment::where('status', 'completed')
            ->whereBetween('paid_at', [$from, $to])
            ->selectRaw('type, SUM(amount) as total, COUNT(*) as count')
            ->groupBy('type')
            ->get();

        $daily = Payment::where('status', 'completed')
            ->whereBetween('paid_at', [$from, $to])
            ->selectRaw('DATE(paid_at) as date, SUM(amount) as total')
            ->groupByRaw('DATE(paid_at)')
            ->orderByRaw('DATE(paid_at)')
            ->get();

        $byMethod = Payment::join('payment_methods', 'payments.payment_method_id', '=', 'payment_methods.id')
            ->where('payments.status', 'completed')
            ->whereBetween('payments.paid_at', [$from, $to])
            ->selectRaw('payment_methods.name as method, SUM(payments.amount) as total, COUNT(*) as count')
            ->groupBy('payment_methods.id', 'payment_methods.name')
            ->get();

        return response()->json(compact('summary', 'daily', 'byMethod'));
    }

    /**
     * GET /api/reports/occupancy
     */
    public function occupancy(Request $request)
    {
        $overview = DB::table('lockers')
            ->selectRaw("
                COUNT(*) as total,
                SUM(IF(status='available',1,0)) as available,
                SUM(IF(status='occupied',1,0)) as occupied,
                SUM(IF(status='maintenance',1,0)) as maintenance,
                ROUND(SUM(IF(status='occupied',1,0)) / NULLIF(SUM(IF(status!='maintenance',1,0)),0) * 100, 1) as occupancy_rate
            ")->first();

        $byCategory = DB::table('lockers')
            ->join('locker_categories', 'lockers.category_id', '=', 'locker_categories.id')
            ->selectRaw("
                locker_categories.name as category,
                COUNT(*) as total,
                SUM(IF(lockers.status='occupied',1,0)) as occupied,
                SUM(IF(lockers.status='available',1,0)) as available
            ")
            ->groupBy('locker_categories.id', 'locker_categories.name')
            ->get();

        $byZone = DB::table('lockers')
            ->join('locker_zones', 'lockers.zone_id', '=', 'locker_zones.id')
            ->selectRaw("
                locker_zones.name as zone,
                COUNT(*) as total,
                SUM(IF(lockers.status='occupied',1,0)) as occupied,
                SUM(IF(lockers.status='available',1,0)) as available
            ")
            ->groupBy('locker_zones.id', 'locker_zones.name')
            ->get();

        return response()->json(compact('overview', 'byCategory', 'byZone'));
    }

    /**
     * GET /api/reports/clients
     */
    public function clients(Request $request)
    {
        $from = $request->get('from', now()->startOfYear()->toDateString());
        $to   = $request->get('to',   now()->toDateString());

        $newPerMonth = Client::selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, COUNT(*) as total')
            ->whereBetween('created_at', [$from, $to])
            ->groupByRaw('YEAR(created_at), MONTH(created_at)')
            ->orderByRaw('YEAR(created_at), MONTH(created_at)')
            ->get();

        $byStatus = Client::selectRaw('status, COUNT(*) as total')->groupBy('status')->get();
        $byGender = Client::selectRaw('gender, COUNT(*) as total')->whereNotNull('gender')->groupBy('gender')->get();

        return response()->json(compact('newPerMonth', 'byStatus', 'byGender'));
    }

    /**
     * GET /api/reports/overdue
     */
    public function overdue()
    {
        $overdue = Rental::overdue()
            ->with(['client', 'locker', 'payments'])
            ->orderBy('end_date')
            ->get()
            ->map(fn($r) => [
                'rental_number' => $r->rental_number,
                'client_name'   => $r->client->full_name,
                'client_phone'  => $r->client->phone,
                'locker_number' => $r->locker->locker_number,
                'end_date'      => $r->end_date,
                'days_overdue'  => $r->daysOverdue(),
                'rental_amount' => $r->rental_amount,
                'key_status'    => $r->key_status,
            ]);

        return response()->json(['overdue' => $overdue, 'total' => count($overdue)]);
    }

    /**
     * GET /api/reports/export/{type}
     */
    public function export(Request $request, string $type)
    {
        // Returns CSV for the given report type
        // Implementation depends on type: revenue, occupancy, overdue, clients
        return response()->json(['message' => "Export for '{$type}' queued."]);
    }
}
