<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class OfficeMobileController extends Controller
{
    /**
     * Get list of all offices.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllOffices(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (!$apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if ($apiKey !== config('app.mobile_api_key')) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Ambil daftar kantor
        $offices = DB::table('tbl_office')
            ->select(
                'id',
                'office_name',
                'office_short_name',
                'address',
                'description',
                'latitude',
                'longitude',
                'status',
                'created_at'
            )
            ->get();

        return response()->json([
            'message' => 'Offices fetched successfully.',
            'data' => $offices,
        ], 200);
    }

    /**
     * Create a new office.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function createOffice(Request $request)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (!$apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if ($apiKey !== config('app.mobile_api_key')) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Validasi input
        $validator = Validator::make($request->all(), [
            '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',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        // Insert data office
        $officeId = DB::table('tbl_office')->insertGetId([
            'office_name' => $request->input('office_name'),
            'office_short_name' => $request->input('office_short_name'),
            'address' => $request->input('address'),
            'description' => $request->input('description'),
            'latitude' => $request->input('latitude'),
            'longitude' => $request->input('longitude'),
            'status' => $request->input('status'),
            'created_at' => now('Asia/Jakarta'),
            'created_by' => $request->input('created_by'),
        ]);

        return response()->json([
            'message' => 'Office created successfully.',
            'office_id' => $officeId,
        ], 201);
    }

    /**
     * Update an office by ID.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateOffice(Request $request, $id)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (!$apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if ($apiKey !== config('app.mobile_api_key')) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Validasi input
        $validator = Validator::make($request->all(), [
            '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',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        // Cek apakah office ada
        $office = DB::table('tbl_office')->where('id', $id)->first();
        if (!$office) {
            return response()->json(['error' => 'Office not found'], 404);
        }

        // Update data office
        DB::table('tbl_office')->where('id', $id)->update([
            'office_name' => $request->input('office_name'),
            'office_short_name' => $request->input('office_short_name'),
            'address' => $request->input('address'),
            'description' => $request->input('description'),
            'latitude' => $request->input('latitude'),
            'longitude' => $request->input('longitude'),
            'status' => $request->input('status'),
            'updated_at' => now('Asia/Jakarta'),
            'modified_by' => $request->input('modified_by'),
        ]);

        return response()->json([
            'message' => 'Office updated successfully.',
        ], 200);
    }

    /**
     * Delete an office by ID.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteOffice(Request $request, $id)
    {
        $apiKey = $request->header('x-api-key');

        // Validasi API Key
        if (!$apiKey) {
            return response()->json(['error' => 'API Key is required'], 400);
        }

        if ($apiKey !== config('app.mobile_api_key')) {
            return response()->json(['error' => 'Invalid API Key'], 401);
        }

        // Cek apakah office ada
        $office = DB::table('tbl_office')->where('id', $id)->first();
        if (!$office) {
            return response()->json(['error' => 'Office not found'], 404);
        }

        // Ubah status menjadi 0 (soft delete)
        DB::table('tbl_office')->where('id', $id)->update([
            'status' => 0,
            'updated_at' => now('Asia/Jakarta'),
            'modified_by' => $request->input('modified_by') // Opsional, menyimpan ID user yang mengubah data
        ]);

        return response()->json([
            'message' => 'Office deactivated successfully.',
        ], 200);
    }
}
