<?php
namespace App\Http\Controllers\API;

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

class OfficeController extends Controller
{
    public function index(Request $request)
    {
        try {
            $itemsPerPage = is_numeric($request->get('itemsPerPage')) ? (int) $request->get('itemsPerPage') : 10;
            $search       = $request->get('search', '');

            $offices = OfficeModel::where('status', "1") // Hanya ambil kantor aktif
                ->where(function ($query) use ($search) {
                    if (! empty($search)) {
                        $query->where('office_name', 'like', "%{$search}%")
                            ->orWhere('office_short_name', 'like', "%{$search}%");
                    }
                })
                ->orderBy('office_name', 'asc')
                ->paginate($itemsPerPage);

            // Konversi status ke integer agar Vue bisa membacanya dengan benar
            $offices->getCollection()->transform(function ($office) {
                $office->status = (int) $office->status;
                return $office;
            });

            return response()->json($offices, 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error fetching offices.', 'error' => $e->getMessage()], 500);
        }
    }

    public function buildingGroupedByOffice()
    {
        try {
            // Fetch all offices with their buildings
            $offices = OfficeModel::with([
                'buildings' => function ($query) {
                    $query->select('id', 'building_name', 'office_id')->where('status', "1");
                },
            ])->select('id', 'office_name')->get();

            return response()->json($offices, 200);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Error fetching grouped office data.',
                'error'   => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Mengembalikan daftar office tanpa paginasi untuk dropdown
     */
    public function getOfficeList()
    {
        try {
            $offices = OfficeModel::where('status', operator: "1")
                ->orderBy('id', 'asc')
                ->get(['id', 'office_name', 'office_short_name']);

            return response()->json([
                'success' => true,
                'data'    => $offices,
            ], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error fetching office list.', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Menyimpan office baru
     */
    public function store(Request $request)
    {
        $request->validate([
            'office_name'       => 'required|string|max:255',
            'office_short_name' => 'required|string|max:100',
            'address'           => 'nullable|string',
            'description'       => 'nullable|string',
            'latitude'          => 'nullable|string',
            'longitude'         => 'nullable|string',
            'status'            => 'required|in:0,1',
        ]);

        try {
            $office = OfficeModel::create($request->all());
            return response()->json($office, 201);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error creating office.', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Update office
     */
    public function update(Request $request, $id)
    {
        $request->validate([
            'office_name'       => 'required|string|max:255',
            'office_short_name' => 'required|string|max:100',
            'address'           => 'nullable|string',
            'description'       => 'nullable|string',
            'latitude'          => 'nullable|string',
            'longitude'         => 'nullable|string',
            'status'            => 'required|in:0,1',
        ]);

        try {
            $office = OfficeModel::findOrFail($id);
            $office->update($request->all());
            return response()->json($office, 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error updating office.', 'error' => $e->getMessage()], 500);
        }
    }

    /**
     * Hapus office
     */
    public function destroy($id)
    {
        try {
            $office = OfficeModel::findOrFail($id);
            $office->delete();
            return response()->json(['message' => 'Office deleted successfully.'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Error deleting office.', 'error' => $e->getMessage()], 500);
        }
    }
}
