<?php
declare(strict_types=1);

namespace App\Modules\ParentApi\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class ProfileController extends ApiController
{
    public function show(Request $request): Response
    {
        $parent = App::getInstance()->currentParent();

        return $this->successResponse([
            'id' => (int) $parent->id,
            'full_name_ar' => $parent->full_name_ar,
            'full_name_en' => $parent->full_name_en,
            'phone' => $parent->phone,
            'secondary_phone' => $parent->secondary_phone,
            'email' => $parent->email,
            'national_id' => $parent->national_id,
            'relationship' => $parent->relationship,
            'notification_preferences' => $parent->notification_preferences_json
                ? json_decode($parent->notification_preferences_json, true)
                : null,
        ]);
    }

    public function update(Request $request): Response
    {
        $parent = App::getInstance()->currentParent();
        $input = $request->jsonBody();
        $db = App::getInstance()->db();

        $allowed = ['full_name_ar', 'full_name_en', 'secondary_phone', 'email', 'notification_preferences_json'];
        $data = [];

        foreach ($allowed as $field) {
            if (array_key_exists($field, $input)) {
                if ($field === 'notification_preferences_json' && is_array($input[$field])) {
                    $data[$field] = json_encode($input[$field], JSON_UNESCAPED_UNICODE);
                } else {
                    $data[$field] = $input[$field];
                }
            }
        }

        if (empty($data)) {
            return $this->errorResponse('لا توجد بيانات للتحديث', 422);
        }

        $db->update('parent_accounts', $data, 'id = ?', [(int) $parent->id]);

        return $this->successResponse(['updated' => true]);
    }
}
