<?php

declare(strict_types=1);

namespace PortalPeople\wordpressbridge\services;

use Yii;
use yii\web\Response;

/**
 * WpService – WordPress integration endpoints.
 *
 * Handles availability sample queries and webhook record creation
 * for WordPress integration.
 */
class WpService
{
    /**
     * Sample availability check for a date range and centre.
     *
     * @return void
     */
    public function sample(): void
    {
        $date1  = Yii::$app->request->post('start');
        $date2  = Yii::$app->request->post('end');
        $center = Yii::$app->request->post('center');

        Yii::$app->response->format     = Response::FORMAT_JSON;
        Yii::$app->response->statusCode = 200;

        if (($date1 !== null && $date1 !== '') && ($date2 !== null && $date2 !== '')) {
            Yii::$app->response->data = [
                'status'       => 200,
                'availability' => 3,
                'europrice'    => 110.00,
                'center'       => $center,
                'message'      => 'Good',
            ];
        } else {
            Yii::$app->response->data = [
                'status'       => 100,
                'availability' => null,
                'europrice'    => null,
                'center'       => $center,
                'message'      => 'No Dates Given',
            ];
        }
    }

    /**
     * Create a WordPress webhook record (Sgwebhooksbe).
     *
     * @return string JSON-encoded status response.
     */
    public function create(): string
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $data = Yii::$app->request->post();
        $hook = new \backend\models\Sgwebhooksbe();

        foreach ($data as $a => $ele) {
            foreach ($ele as $b => $mail) {
                if ($b === 'ip') {
                    $b = 'ipaddress';
                }
                if ($b === 'url_offset') {
                    $mail = json_encode($mail);
                }
                $hook->$b = $mail;
            }
        }

        if ($hook->save()) {
            return json_encode(['status' => 200, 'message' => 'Good']);
        }

        return json_encode(['status' => 100, 'message' => $hook->errors]);
    }
}
