<?php

require_once(__DIR__ . '/vendor/autoload.php');
require_once(__DIR__ . '/gmb_post_factory.php');

class social_api_factory
{
    /**
     * Follows the pattern => 'social_api_factory::create("GoogleMyBusiness")'
     * where the platform options are: GoogleMyBusiness/Facebook/Instagram
     * @param $platform
     * @return facebook_api|google_my_business_api|instagram_api
     * @throws Exception
     */
    public static function create($platform)
    {
        switch ($platform) {
            case 'GoogleMyBusiness':
                return new google_my_business_api();
                break;
            case 'Facebook':
                return new facebook_api();
                break;
            case 'Instagram':
                return new instagram_api();
                break;
            default:
                throw new Exception("Invalid platform specified");
        }
    }
}

interface social_api_factory_base
{
    public function createPost($data);
}


class google_my_business_api implements social_api_factory_base
{
    /**
     * uses google api client library to create a localPost in their Googe My Business - Business Profile
     * requires the user's wp site's url and their wp access token passed in as an array
     * @param $data
     * @return void
     */
    public function createPost($data)
    {
#region getting token data and initializing client library
        $token_data = json_decode(get_option('io_gmb_access'), true);

    //initialize google client
        $json_credentials_path = plugin_dir_path(__FILE__) . 'includes/GMB/GMB_Client_Credentials.json';
        $client = new Google_Client();
        $client->setAuthConfig($json_credentials_path);
        $client->setScopes('https://www.googleapis.com/auth/business.manage');
        $client->setAccessType('offline');

        $token_expiration_time = $token_data["created"] + $token_data["expires_in"];

        if(time() > $token_expiration_time && $token_expiration_time > 0)
        {
            $token_is_expired = TRUE;

        //refresh token data with client
            $refreshed_token_data = $client->fetchAccessTokenWithRefreshToken($token_data["refresh_token"]);
            update_option($data["option_name"], json_encode($refreshed_token_data));

        }

    //set access_token for api client calls
        if ($token_is_expired)
        {
            if (is_array($refreshed_token_data) && $refreshed_token_data[0]) $refreshed_token_data = $refreshed_token_data[0];
            $client->setAccessToken($refreshed_token_data['access_token']);
            $create_token = $refreshed_token_data['access_token'];
        }
        else
        {
            if (is_array($token_data) && $token_data[0]) $token_data = $token_data[0];
            $client->setAccessToken($token_data["access_token"]);
            $create_token = $token_data["access_token"];
        }
#endregion

#region create the post

    //get accounts: account_id
        $account_service = new Google\Service\MyBusinessAccountManagement($client);
        $accounts = $account_service->accounts->listAccounts();

    //init location service and get locations
        $location_service = new Google\Service\MyBusinessBusinessInformation($client);

    //get each accounts locations: location_id
        foreach ($accounts as $account)
        {
            $location = $location_service->accounts_locations->listAccountsLocations($account->name, ['readMask' => 'title,name,websiteUri', 'pageSize' => '100']);

        // Check if the 'locations' property exists and is an array
            if (isset($location->locations) && is_array($location->locations))
            {
                foreach ($location->locations as $locationData)
                {

                //sanitize URLs
                    $url1 = $data["site_url"];
                    $url2 = $locationData->websiteUri;

                    $url1 = preg_replace('#^https?://#i', '', $url1);
                    $url2 = preg_replace('#^https?://#i', '', $url2);

                    $url1 = preg_replace('#^www\.#i', '', $url1);
                    $url2 = preg_replace('#^www\.#i', '', $url2);

                    if (!str_ends_with($url1, "/")) $url1 .= "/";


                //checks for a match between the site that sent us here and the sites returned by google as locations
                    if ($url1 == $url2)
                    {

                    //create an instance of the gmb post factory and pass necessary data through
                        $post_factory = gmb_post_factory::create();
                        $post_data = $post_factory->createPost($data);
                        $post_data_json = json_encode($post_data);

                    //Make the curl call using the post data we constructed
                        $api_url = 'https://mybusiness.googleapis.com/v4/' . $account->name . '/' . $locationData->name . '/localPosts';

                        $ch = curl_init();
                        curl_setopt($ch, CURLOPT_URL, $api_url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                            'Authorization: Bearer ' . $create_token,
                            'Content-Type: application/json',
                            'Content-Length: ' . strlen($post_data_json),
                        ));
                        curl_setopt($ch, CURLOPT_POST, true);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_json);
                        $response = curl_exec($ch);
                        curl_close($ch);

                        if (strpos($response, 'accounts') !== false) {
                            return TRUE;
                        } else {
                            echo $response;
                            return False;
                        }
                    }
                }
            }
            else
            {
                echo "Unable to retrieve locations. Please ensure the provided address is valid.";
            }
        }
#endregion
    }
}

class facebook_api implements social_api_factory_base
{
    public function createPost($data)
    {
        // Code to create a post on Twitter
    }
}

class instagram_api implements social_api_factory_base
{
    public function createPost($data)
    {
        // Code to create a post on Instagram
    }
}

/* Example usage

$facebook = SocialMediaAPI::create("Facebook");
$facebook->createPost(array("message" => "Hello, World!"));

$twitter = SocialMediaAPI::create("Twitter");
$twitter->createPost(array("message" => "Hello, World!"));

$instagram = SocialMediaAPI::create("Instagram");
$instagram->createPost(array("message" => "Hello, World!", "image" => "image.jpg"));
*/