<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Kasbon;
use Illuminate\Http\Request;
use Exception;

class KasbonApiController extends Controller
{
    /**
     * GET - Riwayat kasbon teknisi
     */
    public function riwayat(Request $request)
    {
        try {
            $idTeknisi = $request->input('id_teknisi');

            if (!$idTeknisi) {
                return response()->json([
                    'success' => false,
                    'message' => 'ID Teknisi tidak ditemukan'
                ], 401);
            }

            $query = Kasbon::where('id_teknisi', $idTeknisi)
                ->orderBy('tanggal_kasbon', 'desc');

            if ($request->filled('status')) {
                $query->where('status', $request->status);
            }

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

            $riwayat->getCollection()->transform(function ($item) {
                return [
                    'id_kasbon'      => $item->id_kasbon,
                    'nominal'        => (float) $item->jumlah_kasbon,
                    'tanggal'        => $item->tanggal_kasbon->format('d M Y'),
                    'keperluan'      => $item->keperluan,
                    'detail'         => $item->keterangan_detail,
                    'status'         => $item->status,
                    'status_label'   => $item->status == 'lunas' ? 'Lunas' : 'Belum Lunas',
                ];
            });

            return response()->json([
                'success' => true,
                'message' => 'Riwayat kasbon berhasil diambil',
                'data'    => $riwayat
            ]);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil data: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * GET - Statistik kasbon (total hutang)
     */
    public function statistik(Request $request)
    {
        try {
            $idTeknisi = $request->input('id_teknisi');

            if (!$idTeknisi) {
                return response()->json([
                    'success' => false,
                    'message' => 'ID Teknisi tidak ditemukan'
                ], 401);
            }

            $totalHutang = Kasbon::where('id_teknisi', $idTeknisi)
                ->where('status', 'belum_lunas')
                ->sum('jumlah_kasbon');

            return response()->json([
                'success' => true,
                'message' => 'Statistik kasbon berhasil diambil',
                'data'    => [
                    'total_hutang' => (float) $totalHutang
                ]
            ]);

        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil statistik: ' . $e->getMessage()
            ], 500);
        }
    }
}
