<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class MaintenanceController extends Controller
{
    protected $maintenanceService;

    public function __construct(\App\Services\MaintenanceService $maintenanceService)
    {
        $this->maintenanceService = $maintenanceService;
    }

    // GET /api/maintenance/bills
    public function index(Request $request)
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return $this->error('Unauthorized', 403);
        }

        $query = DB::table('maintenance_bills')
            ->join('units', 'maintenance_bills.unit_id', '=', 'units.id')
            ->where('maintenance_bills.society_id', $user->society_id)
            ->select('maintenance_bills.*', 'units.unit_number', 'units.wing');

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

        if ($request->has('billing_month')) {
            $query->where('maintenance_bills.billing_month', $request->billing_month);
        }

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where('units.unit_number', 'like', "%{$search}%");
        }

        $bills = $query->orderBy('maintenance_bills.billing_month', 'desc')->paginate(10);

        return $this->success($bills);
    }

    // POST /api/maintenance/generate
    public function generateBills(Request $request)
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return $this->error('Unauthorized', 403);
        }

        $validator = Validator::make($request->all(), [
            'billing_month' => 'required|date_format:Y-m'
        ]);

        if ($validator->fails()) {
            return $this->error('Validation failed', 422, $validator->errors());
        }

        try {
            $count = $this->maintenanceService->generateBills($user->society_id, $request->billing_month);

            if ($count === 0) {
                return $this->success(null, "Bills are up to date for {$request->billing_month}");
            }
            return $this->success(['count' => $count], "Generated {$count} new bills for {$request->billing_month}", 201);

        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 500);
        }
    }

    // POST /api/maintenance/bills/{id}/pay
    public function recordPayment(Request $request, $id)
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return $this->error('Unauthorized', 403);
        }

        try {
            $ledgerId = $this->maintenanceService->recordPayment($id, $user->society_id);
            return $this->success(['ledger_entry_id' => $ledgerId], 'Payment recorded successfully');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), 400); // 400 because mostly it's logical error like 'already paid'
        }
    }

    // GET /api/maintenance/summary
    public function summary()
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403);
        }

        $currentMonth = now()->format('Y-m');

        $stats = DB::table('maintenance_bills')
            ->where('society_id', $user->society_id)
            ->where('billing_month', $currentMonth)
            ->select(
                DB::raw("SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as pending_amount"),
                DB::raw("SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END) as collected_amount"),
                DB::raw("COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count")
            )
            ->first();

        return response()->json([
            'status' => 'success',
            'month' => $currentMonth,
            'pending_amount' => $stats->pending_amount ?? 0,
            'collected_amount' => $stats->collected_amount ?? 0,
            'pending_count' => $stats->pending_count ?? 0
        ]);
    }

    // GET /api/maintenance/history-status
    public function historyStatus()
    {
        $user = Auth::user();
        if (!$user || !$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'Unauthorized'], 403);
        }

        // Check last 6 months
        $months = [];
        for ($i = 0; $i < 6; $i++) {
            $months[] = now()->subMonths($i)->format('Y-m');
        }

        $existingMonths = DB::table('maintenance_bills')
            ->where('society_id', $user->society_id)
            ->whereIn('billing_month', $months)
            ->distinct()
            ->pluck('billing_month')
            ->toArray();

        $status = [];
        foreach ($months as $m) {
            $status[$m] = in_array($m, $existingMonths);
        }

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