<?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 FinanceController extends Controller
{
    // GET /api/finance
    public function index(Request $request)
    {
        $user = Auth::user();
        if (!$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'User not associated with a society'], 403);
        }

        $query = DB::table('account_ledgers')
            ->where('society_id', $user->society_id)
            ->orderBy('transaction_date', 'desc')
            ->orderBy('created_at', 'desc');

        if ($request->has('type')) {
            $query->where('type', $request->type);
        }

        if ($request->has('start_date') && $request->has('end_date')) {
            $query->whereBetween('transaction_date', [$request->start_date, $request->end_date]);
        }

        if ($request->has('search')) {
            $search = $request->query('search');
            $query->where(function ($q) use ($search) {
                $q->where('category', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%");
            });
        }

        $ledger = $query->paginate(15);

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

    // POST /api/finance
    public function store(Request $request)
    {
        $user = Auth::user();
        if (!$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'User not associated with a society'], 403);
        }

        $validator = Validator::make($request->all(), [
            'type' => 'required|in:credit,debit',
            'amount' => 'required|numeric|min:0.01',
            'category' => 'required|string|max:255',
            'transaction_date' => 'required|date',
            'description' => 'nullable|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
        }

        $id = DB::table('account_ledgers')->insertGetId([
            'society_id' => $user->society_id,
            'type' => $request->type,
            'amount' => $request->amount,
            'category' => $request->category,
            'transaction_date' => $request->transaction_date,
            'description' => $request->description,
            'created_at' => now(),
            'updated_at' => now()
        ]);

        return response()->json(['status' => 'success', 'message' => 'Entry added successfully', 'id' => $id], 201);
    }

    // GET /api/finance/summary
    public function summary()
    {
        $user = Auth::user();
        if (!$user->society_id) {
            return response()->json(['status' => 'error', 'message' => 'User not associated with a society'], 403);
        }

        // Calculate totals for the current society
        $stats = DB::table('account_ledgers')
            ->where('society_id', $user->society_id)
            ->select(
                DB::raw("SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) as total_income"),
                DB::raw("SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) as total_expense")
            )
            ->first();

        $balance = $stats->total_income - $stats->total_expense;

        return response()->json([
            'status' => 'success',
            'income' => $stats->total_income,
            'expense' => $stats->total_expense,
            'balance' => $balance
        ]);
    }
}
