<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CashDesk;
use Illuminate\Http\Request;

class CashDeskController extends Controller
{
    public function index()
    {
        return response()->json([
            'status' => 'success',
            'data' => CashDesk::with(['responsible:id,name', 'bankAccount'])->get()
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => 'required|in:bank,staff,guide,office',
            'responsible_id' => 'nullable|exists:users,id',
            'bank_account_id' => 'nullable|exists:bank_accounts,id',
            'is_active' => 'boolean',
        ]);

        $cashDesk = CashDesk::create($validated);

        return response()->json([
            'status' => 'success',
            'message' => 'Kasa başarıyla oluşturuldu.',
            'data' => $cashDesk
        ]);
    }

    public function show(CashDesk $cashDesk)
    {
        return response()->json([
            'status' => 'success',
            'data' => $cashDesk->load(['responsible:id,name', 'bankAccount'])
        ]);
    }

    public function update(Request $request, CashDesk $cashDesk)
    {
        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'type' => 'sometimes|required|in:bank,staff,guide,office',
            'responsible_id' => 'nullable|exists:users,id',
            'bank_account_id' => 'nullable|exists:bank_accounts,id',
            'is_active' => 'boolean',
        ]);

        $cashDesk->update($validated);

        return response()->json([
            'status' => 'success',
            'message' => 'Kasa başarıyla güncellendi.',
            'data' => $cashDesk
        ]);
    }

    public function destroy(CashDesk $cashDesk)
    {
        // Ödemesi olan kasa silinemez olmalı veya kontrol edilmeli
        if ($cashDesk->payments()->count() > 0) {
            return response()->json([
                'status' => 'error',
                'message' => 'İşlem görmüş olan bir kasa silinemez.'
            ], 422);
        }

        $cashDesk->delete();

        return response()->json([
            'status' => 'success',
            'message' => 'Kasa başarıyla silindi.'
        ]);
    }
}
