<?php

namespace App\Controllers\Api;

use App\Libraries\JwtAuth;
use App\Models\LocationModel;

class AddressesController extends BaseApiController
{
    /**
     * GET api/addresses - list current user's saved addresses
     */
    public function index()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $model = model(LocationModel::class);
        $list  = $model->where('user_id', $user->id)->orderBy('is_default', 'DESC')->findAll();
        $data  = array_map(static function ($row) {
            return [
                'id'           => (int) $row->id,
                'latitude'     => (float) $row->latitude,
                'longitude'    => (float) $row->longitude,
                'address_name' => $row->address_name,
                'plus_code'    => $row->plus_code ?? null,
                'is_default'   => (bool) $row->is_default,
            ];
        }, $list);
        return $this->success($data);
    }

    /**
     * POST api/addresses - add address
     */
    public function create()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $json = $this->request->getJSON(true) ?: [];
        $lat  = (float) ($json['latitude'] ?? 0);
        $lng  = (float) ($json['longitude'] ?? 0);
        $name = trim((string) ($json['address_name'] ?? ''));
        $plusCode = trim((string) ($json['plus_code'] ?? '')) ?: null;
        $default = ! empty($json['is_default']);
        if ($lat === 0.0 && $lng === 0.0) {
            return $this->error('latitude and longitude required', 400);
        }
        $model = model(LocationModel::class);
        if ($default) {
            $model->where('user_id', $user->id)->set(['is_default' => 0])->update();
        }
        $model->insert([
            'user_id'      => $user->id,
            'latitude'     => $lat,
            'longitude'    => $lng,
            'address_name' => $name ?: null,
            'plus_code'    => $plusCode,
            'is_default'   => $default ? 1 : 0,
        ]);
        $id = $model->getInsertID();
        $row = $model->find($id);
        return $this->success([
            'id'           => (int) $row->id,
            'latitude'     => (float) $row->latitude,
            'longitude'    => (float) $row->longitude,
            'address_name' => $row->address_name,
            'plus_code'    => $row->plus_code ?? null,
            'is_default'   => (bool) $row->is_default,
        ], 201);
    }

    /**
     * PATCH api/addresses/(:num) - update address
     */
    public function update(int $id)
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $model = model(LocationModel::class);
        $row   = $model->where('user_id', $user->id)->find($id);
        if (! $row) {
            return $this->error('Address not found', 404);
        }
        $json = $this->request->getJSON(true) ?: [];
        $data = [];
        if (array_key_exists('latitude', $json)) {
            $data['latitude'] = (float) $json['latitude'];
        }
        if (array_key_exists('longitude', $json)) {
            $data['longitude'] = (float) $json['longitude'];
        }
        if (array_key_exists('address_name', $json)) {
            $data['address_name'] = trim((string) $json['address_name']) ?: null;
        }
        if (array_key_exists('plus_code', $json)) {
            $data['plus_code'] = trim((string) $json['plus_code']) ?: null;
        }
        if (! empty($json['is_default'])) {
            $model->where('user_id', $user->id)->set(['is_default' => 0])->update();
            $data['is_default'] = 1;
        }
        if ($data !== []) {
            $model->update($id, $data);
        }
        $row = $model->find($id);
        return $this->success([
            'id'           => (int) $row->id,
            'latitude'     => (float) $row->latitude,
            'longitude'    => (float) $row->longitude,
            'address_name' => $row->address_name,
            'plus_code'    => $row->plus_code ?? null,
            'is_default'   => (bool) $row->is_default,
        ]);
    }

    /**
     * DELETE api/addresses/(:num)
     */
    public function delete(int $id)
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $model = model(LocationModel::class);
        $row   = $model->where('user_id', $user->id)->find($id);
        if (! $row) {
            return $this->error('Address not found', 404);
        }
        $model->delete($id);
        return $this->success(['deleted' => true]);
    }
}
