<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\CustomerSettlement;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CustomerSettlementController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $query = CustomerSettlement::forTenant($tenantId);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('customer', 'like', "%{$search}%");
            });
        }
        if ($status = $request->input('status')) {
            if ($status !== 'all') {
                $query->where('status', $status);
            }
        }

        $settlements = $query->orderBy('created_at', 'desc')->get()->map(fn ($item) => [
            'id' => $item->id, 'period' => $item->period,
            'customer' => $item->customer, 'totalSales' => $item->total_sales,
            'commission' => $item->commission, 'expense' => $item->expense,
            'netAmount' => $item->net_amount, 'status' => $item->status,
            'settledDate' => $item->settled_date?->format('Y-m-d'), 'memo' => $item->memo,
        ]);

        $all = CustomerSettlement::forTenant($tenantId)->get();
        $stats = [
            'totalSales' => $all->sum('total_sales'),
            'totalCommission' => $all->sum('commission'),
            'totalNet' => $all->sum('net_amount'),
            'settledAmount' => $all->where('status', 'settled')->sum('net_amount'),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate(['customer' => 'required|string|max:100']);
        $tenantId = session('selected_tenant_id', 1);

        CustomerSettlement::create([
            'tenant_id' => $tenantId, 'period' => $request->input('period'),
            'customer' => $request->input('customer'),
            'total_sales' => $request->input('totalSales', 0),
            'commission' => $request->input('commission', 0),
            'expense' => $request->input('expense', 0),
            'net_amount' => $request->input('netAmount', 0),
            'status' => $request->input('status', 'pending'),
            'settled_date' => $request->input('settledDate'), 'memo' => $request->input('memo'),
        ]);

        return response()->json(['success' => true, 'message' => '정산이 등록되었습니다.']);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $item = CustomerSettlement::forTenant($tenantId)->findOrFail($id);
        $request->validate(['customer' => 'required|string|max:100']);

        $item->update([
            'period' => $request->input('period', $item->period),
            'customer' => $request->input('customer'),
            'total_sales' => $request->input('totalSales', $item->total_sales),
            'commission' => $request->input('commission', $item->commission),
            'expense' => $request->input('expense', $item->expense),
            'net_amount' => $request->input('netAmount', $item->net_amount),
            'status' => $request->input('status', $item->status),
            'settled_date' => $request->input('settledDate'), 'memo' => $request->input('memo'),
        ]);

        return response()->json(['success' => true, 'message' => '정산이 수정되었습니다.']);
    }

    public function destroy(int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        CustomerSettlement::forTenant($tenantId)->findOrFail($id)->delete();

        return response()->json(['success' => true, 'message' => '정산이 삭제되었습니다.']);
    }
}
