<?php

namespace App\Http\Controllers\Finance;

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

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

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

        $records = $query->orderBy('date', 'desc')->get()->map(fn ($item) => [
            'id' => $item->id, 'date' => $item->date?->format('Y-m-d'),
            'customer' => $item->customer, 'project' => $item->project,
            'type' => $item->type, 'taxType' => $item->tax_type ?? 'taxable',
            'amount' => $item->amount, 'vat' => $item->vat, 'status' => $item->status,
            'invoiceNo' => $item->invoice_no, 'memo' => $item->memo,
        ]);

        $all = SalesRecord::forTenant($tenantId)->get();
        $stats = [
            'totalAmount' => $all->sum('amount'),
            'totalVat' => $all->sum('vat'),
            'confirmedAmount' => $all->where('status', 'completed')->sum('amount'),
            'contractedAmount' => $all->whereIn('status', ['contracted', 'invoiced'])->sum('amount'),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'customer' => 'required|string|max:100',
            'amount' => 'required|integer|min:0',
            'taxType' => 'nullable|in:taxable,zero_rated,exempt',
        ]);
        $tenantId = session('selected_tenant_id', 1);

        SalesRecord::create([
            'tenant_id' => $tenantId, 'date' => $request->input('date'),
            'customer' => $request->input('customer'), 'project' => $request->input('project'),
            'type' => $request->input('type'), 'tax_type' => $request->input('taxType', 'taxable'),
            'amount' => $request->input('amount', 0), 'vat' => $request->input('vat', 0),
            'status' => $request->input('status', 'contracted'),
            'invoice_no' => $request->input('invoiceNo'), '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 = SalesRecord::forTenant($tenantId)->findOrFail($id);
        $request->validate([
            'customer' => 'required|string|max:100',
            'amount' => 'required|integer|min:0',
            'taxType' => 'nullable|in:taxable,zero_rated,exempt',
        ]);

        $item->update([
            'date' => $request->input('date'), 'customer' => $request->input('customer'),
            'project' => $request->input('project'), 'type' => $request->input('type', $item->type),
            'tax_type' => $request->input('taxType', $item->tax_type),
            'amount' => $request->input('amount'), 'vat' => $request->input('vat', $item->vat),
            'status' => $request->input('status', $item->status),
            'invoice_no' => $request->input('invoiceNo'), 'memo' => $request->input('memo'),
        ]);

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

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

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