111

111

11
<?php

namespace Codefantasy\Wealty\Plugin\GreatSchools;

use Codefantasy\Theme\Core\Application\AbstractServiceProvider;
use Codefantasy\Theme\Core\Application\Application;
use Codefantasy\Theme\Core\Clientside\JsonResponse;
use Codefantasy\Theme\Core\Common\Util;
use Codefantasy\Theme\Core\Component\Logger\SilentExceptionLogger;
use Codefantasy\Theme\Core\Component\VisualComposer\Element\ElementBuilder\SimpleElementBuilder;
use Codefantasy\Theme\Core\Component\VisualComposer\Element\ElementBuilder\SimpleElementView;
use Codefantasy\Theme\Core\Exception;
use Codefantasy\Wealty\Plugin\MetaFieldType\Map\DisplayConfig\ElementView;
use Codefantasy\Wealty\Plugin\VcIntegration\OptionFactory;
use Codefantasy\Wealty\Plugin\VcIntegration\OptionTypes\FieldDropdownView;
use Symfony\Component\HttpFoundation\Request;
use function Codefantasy\Theme\Core\Application\app;
use function Codefantasy\Theme\Core\Asset\get;


class Init extends AbstractServiceProvider
{

    private static $states = [
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
        'AR' => 'Arkansas',
        'CA' => 'California',
        'CO' => 'Colorado',
        'CT' => 'Connecticut',
        'DE' => 'Delaware',
        'DC' => 'District of Columbia',
        'FL' => 'Florida',
        'GA' => 'Georgia',
        'HI' => 'Hawaii',
        'ID' => 'Idaho',
        'IL' => 'Illinois',
        'IN' => 'Indiana',
        'IA' => 'Iowa',
        'KS' => 'Kansas',
        'KY' => 'Kentucky',
        'LA' => 'Louisiana',
        'ME' => 'Maine',
        'MD' => 'Maryland',
        'MA' => 'Massachusetts',
        'MI' => 'Michigan',
        'MN' => 'Minnesota',
        'MS' => 'Mississippi',
        'MO' => 'Missouri',
        'MT' => 'Montana',
        'NE' => 'Nebraska',
        'NV' => 'Nevada',
        'NH' => 'New Hampshire',
        'NJ' => 'New Jersey',
        'NM' => 'New Mexico',
        'NY' => 'New York',
        'NC' => 'North Carolina',
        'ND' => 'North Dakota',
        'OH' => 'Ohio',
        'OK' => 'Oklahoma',
        'OR' => 'Oregon',
        'PA' => 'Pennsylvania',
        'RI' => 'Rhode Island',
        'SC' => 'South Carolina',
        'SD' => 'South Dakota',
        'TN' => 'Tennessee',
        'TX' => 'Texas',
        'UT' => 'Utah',
        'VT' => 'Vermont',
        'VA' => 'Virginia',
        'WA' => 'Washington',
        'WV' => 'West Virginia',
        'WI' => 'Wisconsin',
        'WY' => 'Wyoming',
    ];

    const CALLBACK_ROUTE = 'getNearbySchoolsByCoordinates';

    public function boot_vc(Application $app)
    {
        $factory = $app->getVcFactory();
        $factory->createSimpleElement('wealty_great_schools',
            function (SimpleElementBuilder $elementBuilder, OptionFactory $of) use ($app) {
                $elementBuilder
                    ->setName('Great Schools')
                    ->setTemplate(function (SimpleElementView $view) {
                        return Util::renderPHPTemplate(
                            __DIR__ . '/../MetaFieldType/Resources/templates/component-wrapper.php',
                            [
                                'elementView' => $view,
                                'containerClasses' => 'great-schools__wrap--main' . $view->option('design'),
                                'wrapWithExtraDiv' => true
                            ]
                        );
                    })
                    ->setJsName('greatSchools')
                    ->setJsVars(function (SimpleElementView $view) {

                        $lat = $lng = $address = '';

                        if ($view->option('use_property_location')) {
                            /** @var FieldDropdownView $options */
                            $options = $view->option('options', true);

                            try {
                                /** @var ElementView $locationView */
                                $locationView = $options->getView();
                                $lat = $locationView->lat();
                                $lng = $locationView->lng();
                            } catch (Exception $exception) {
                                /** @var SilentExceptionLogger $exceptionHandler */
                                $exceptionHandler = app('logger.silent_exception_handler');
                                $exceptionHandler->handleException($exception);
                            }

                        } else {
                            $lat = $view->option('lat');
                            $lng = $view->option('lng');
                        }

                        if ($view->option('use_custom_radius')) {
                            $rad = $view->option('rad');
                        } else {
                            $rad = 10000;
                        }

                        return [
                            'design' => $view->option('design'),
                            'title' => $view->option('title'),
                            'divider' => $view->option('divider'),
                            'header' => $view->option('header'),
                            'headerTitle' => $view->option('header_title'),
                            'lmt' => $view->option('lmt'),
                            'state' => $view->option('state'),
                            'lng' => $lng,
                            'lat' => $lat,
                            'rad' => $rad,
                            'callbackRoute' => self::CALLBACK_ROUTE,
//                            'address' => $address,
                            'i18n' => [
                                'miles' => esc_html__('mi', 'wealty'),
                                'reviews' => esc_html__('reviews', 'wealty'),
                                'powered' => esc_html__('powered by', 'wealty'),
                                'out' => esc_html__('Out of ', 'wealty'),
                                'nodata' => esc_html__('No data. Try changing parameters and required fields', 'wealty'),
                                'rating' => esc_html__('School rating', 'wealty'),
                                'students' => esc_html__('students', 'wealty'),
                                'Students' => esc_html__('Students', 'wealty'),
                                'Grades' => esc_html__('Grades', 'wealty'),
                                'Distances' => esc_html__('Distances', 'wealty'),
                            ],
                        ];
                    })
                    ->setParams(
//                        $of->dropdown('design')
//                            ->label(esc_html__('Design style', 'wealty'))
//                            ->options([
//                                'Default' => 'default',
//                            ]),
//                        $of->textInput('address')
//                            ->label(esc_html__('Address', 'wealty'))
//                            ->dependency([
//                                'element' => 'use_property_location',
//                                'is_empty' => true,
//                            ]),
//                        $of
//                            ->textInput('title')
//                            ->label(esc_html__('Title', 'wealty')),
                        $of
                            ->textInput('lmt')
                            ->label(esc_html__('Limit', 'wealty')),
                        $of->checkbox('use_property_location')
                            ->label(esc_html__("Use property location", 'wealty')),
                        $of->textInput('lat')
                            ->label(esc_html__('Latitude', 'wealty'))
                            ->dependency([
                                'element' => 'use_property_location',
                                'is_empty' => true,
                            ]),
                        $of->textInput('lng')
                            ->label(esc_html__('Longitude', 'wealty'))
                            ->dependency([
                                'element' => 'use_property_location',
                                'is_empty' => true,
                            ]),
                        $of->metaFieldDropdown('options')
                            ->label(esc_html__("Select field config", 'wealty'))
                            ->dependency([
                                'element' => 'use_property_location',
                                'value' => '1',
                            ]),
                        $of->checkbox('use_custom_radius')
                            ->label(esc_html__("Use custom radius", 'wealty')),
                        $of->textInput('rad')
                            ->label(esc_html__('Miles radius to confine search to. 
                            Default: 5. Maximum: 50', 'wealty'))
                            ->dependency([
                                'element' => 'use_custom_radius',
                                'value' => '1',
                            ]),
                        $of->cssEditor('css')
                            ->label(esc_html__('CSS', 'wealty'))
                            ->group(esc_html__('Design options', 'wealty')),
//                        $of->checkbox('divider')
//                            ->label(esc_html__("Use divider between items for mobile", 'wealty')),
                        $of->checkbox('header')
                            ->label(esc_html__("Add header with title and powered by Great Schools logo", 'wealty')),
                        $of->textInput('header_title')
                            ->label(esc_html__('Header title', 'wealty'))
                            ->dependency([
                                'element' => 'header',
                                'value' => '1',
                            ])
                    );
            });
    }

    public function boot(Application $app)
    {
        $app['ajax']->add_listener(self::CALLBACK_ROUTE, function (Request $request) use ($app) {

            $lat = $request->request->get('lat');
            $rad = $request->request->get('rad');
            $lng = $request->request->get('lng');
            $lmt = $request->request->get('lmt');

            $stateLoaderURL = add_query_arg([
                'f' => 'pjson',
                'lat' => $lat,
                'lon' => $lng,
                'featureTypes' => 'PointAddress',
                'location' => "$lng,$lat",
            ], 'http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode');

            $response = wp_remote_get(esc_url_raw($stateLoaderURL));
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $longStateName = get($body['address']['Region']);
            if (!$longStateName) {
                throw new Exception('Nominantim did not return a valid response');
            }

            $shortStateName = array_search($longStateName, self::$states, false);
            if (!$shortStateName) {
                throw new Exception("The abbeviation for the state {$body['state']} was not found");
            }

            $url = add_query_arg([
                'key' => '110be00bb92aa9bfd5d4d5fbdf7e335b',
                'lat' => $lat,
                'lon' => $lng,
                'state' => $shortStateName,
                'limit' => $lmt,
                'radius' => $rad,
            ], 'https://api.greatschools.org/schools/nearby');


            $response = wp_remote_get(esc_url_raw($url), [
                'headers' => [
                    'Accept' => 'application/json',
                ],
            ]);
            $reponseBody = json_decode(wp_remote_retrieve_body($response), true);
            $rawData = get($reponseBody['schools']['school'], []);
            return new JsonResponse([
                'result' => $rawData,
            ], 200, true);
        });
    }
}


Report Page