<?php

class agile_tix_amy_movie_integrate
{
    private $agile_tix;
    private $version;

    public function __construct($agile_tix, $version)
    {
        $this->agile_tix = $agile_tix;
        $this->version = $version;
    }

    static function agile_amy_movie_post_creator($event, $commentStat, $postStat, $isNewEvent, $postID, $comingSoonEventData = null)
    {
        // Coming soon events never have CurrentShowings
        $currentShowings = isset($event['CurrentShowings']) && is_array($event['CurrentShowings']) ? $event['CurrentShowings'] : [];
        $firstShowing = !empty($currentShowings) ? $currentShowings[0] : [];
        $lastShowing = !empty($currentShowings) ? $currentShowings[count($currentShowings) - 1] : [];

        $types = [];
        $values = [];
        if (!empty($event['AdditionalMedia'])) {
            foreach ($event['AdditionalMedia'] as $media) {
                $types[] = $media['Type'];
                $values[] = $media['Value'];
            }
        }
        $typeString = implode(',', $types);
        $valueString = implode(',', $values);

        $CustomProperties = agile_tix_amy_movie_integrate::groupCustomProperties($event);

        $ratingValue = '';
        if (array_key_exists('Rating', $CustomProperties)) {
            $ratingValue = $CustomProperties['Rating'];
        }

        $langaugeValue = '';
        if (array_key_exists('Original Langauge', $CustomProperties)) {
            $langaugeValue = $CustomProperties['Original Langauge'];
        }

        $thumbnailID = '';
        if (!empty($event['EventImage'])) {
            $mediaLibImg = agile_tix_post_creator::add_image_to_media_library_from_uri($event['EventImage']);
            if ($mediaLibImg && array_key_exists('url', $mediaLibImg) && array_key_exists('attachment_id', $mediaLibImg)) {
                $thumbnailID = $mediaLibImg['attachment_id'];
            }
        }

        $showingIDs = [];
        foreach ($currentShowings as $showing) {
            array_push($showingIDs, $showing["ID"]);
        }


        $metaBase = agile_tix_post_creator::agile_create_universal_meta_fields($event, $thumbnailID, $comingSoonEventData);
        // Handle empty CurrentShowings (coming soon events never have CurrentShowings)
        $metaBase['_duration'] = !empty($firstShowing['Duration']) ? $firstShowing['Duration'] : '';
        $metaBase['_layout'] = 'full';
        $metaBase['_showtimes'] = !empty($firstShowing) ? agile_tix_amy_movie_integrate::ats_SerializeShowTicketsArea($firstShowing['LegacyPurchaseLink'] ?? '', $firstShowing['SalesMessage'] ?? '', $firstShowing['StartDate'] ?? '') : '';
        $metaBase['_start_date'] = !empty($firstShowing['StartDate']) ? agile_tix_event_champ_integrate::ats_DateFormat($firstShowing['StartDate']) : '';
        $metaBase['_end_date'] = !empty($lastShowing['EndDate']) ? agile_tix_event_champ_integrate::ats_DateFormat($lastShowing['EndDate']) : '';
        $metaBase['_language'] = $langaugeValue;
        $metaBase['_mpaa'] = $ratingValue;
        $metaBase['amy_imdb_movie'] = '1';
        $metaBase['custom_rating'] = '0';
        $metaBase['_imdb'] = "N/A";// TODO: come back and see if these can be set better

        $post_data = array(
            'ID' => $postID,
            'post_title' => $event['Name'],
            'post_content' => agile_tix_post_creator::agile_create_universal_content_body($event) . '<div class="hiddenTags">\r\n\r\n&nbsp;\r\n\r\n&nbsp;\r\n\r\n' . $event['CorpOrgName'] . '</div> ',
            'post_name' => agile_tix_event_champ_integrate::ats_FormatEventSlug($event['Name'], $event['ID']),
            'post_status' => $postStat,
            'post_type' => 'amy_movie',
            //'post_author' => get_user_by('id', 1)->user_id,
            'comment_status' => $commentStat,
            /*'meta_input' => array( //meta data
                //required non-eventchamp meta for ats post searching
                //"ATS_ModifiedDate" => agile_tix_post_creator::agile_get_most_recent_lastUpdate($event) ?? '',
                //"ATS_firstEndDate" => $event['CurrentShowings'][0]['EndDate'] ?? '',
                //"ATS_showingIDs" => $showingIDs ?? [],
                //'OrgID' => $event['OrgID'] ?? '',
                //'CorpOrgID' => $event['CorpOrgID'] ?? '',
                // "ATS_EventID" => $event['ID'] ?? '',
                //"ATS_MediaLib_Img_ID" => $thumbnailID ?? '',
                //"ATS_HideFeatImg" => get_option('agile_field_render_carousel') ?? 0,
                //amy movie specific fields
                
            ),*/
            'meta_input' => $metaBase
        );

        if ($isNewEvent) {
            $postID = wp_insert_post($post_data);
        } else {
            $postID = wp_update_post($post_data);
        }
        update_post_meta($postID, '_poster', agile_tix_amy_movie_integrate::ats_PosterImage($event['EventImage']));
        update_post_meta($postID, '_trailer', agile_tix_amy_movie_integrate::ats_HasTrailer($typeString, $valueString));

        if (array_key_exists('Genre', $CustomProperties)) {
            wp_set_object_terms($postID, $CustomProperties['Genre'], 'amy_genre');
        }

        if (array_key_exists('Cast', $CustomProperties)) {
            wp_set_object_terms($postID, $CustomProperties['Cast'], 'amy_actor');
        }

        if (array_key_exists('Director', $CustomProperties)) {
            wp_set_object_terms($postID, $CustomProperties['Director'], 'amy_director');
        }
    }

    static function image_exists_in_media_library($image_url)
    {
        global $wpdb;

        $file_name = basename($image_url);

        $query = $wpdb->get_var(
            $wpdb->prepare(
                "SELECT ID FROM {$wpdb->posts}
             WHERE post_type = 'attachment'
             AND post_mime_type LIKE 'image/%'
             AND guid LIKE %s",
                '%' . $file_name
            )
        );

        return !empty($query) ? $query : false;
    }

    static function ats_GetImageID($image_url)
    {
        $image_exists = agile_tix_amy_movie_integrate::image_exists_in_media_library($image_url);

        if ($image_exists !== false) {
            return $image_exists;
        } else {
            return 0;
        }
    }

    static function ats_PosterImage($img_url)
    {
        $imgID = agile_tix_amy_movie_integrate::ats_GetImageID($img_url);
        $image_url = "";
        $width = 0;
        $height = 0;
        $title = "";
        $desc = "";
        $thumb_url = "";


        if ($imgID > 0) {
            if ($imgID) {
                $image_info_full = wp_get_attachment_image_src($imgID, 'full');
                $image_info_thumb = wp_get_attachment_image_src($imgID, 'thumbnail');

                if ($image_info_full) {
                    $image_url = $image_info_full[0];
                    $width = $image_info_full[1];
                    $height = $image_info_full[2];
                    $title = get_the_title($imgID);
                    $desc = get_post_field('post_content', $imgID);
                } 
            }
            $outer = array("url" => $image_url, "id" => strval($imgID), "width" => strval($width), "height" => strval($height), "thumbnail" => $image_info_thumb[0], "alt" => get_post_meta($imgID, '_wp_attachment_image_alt', true), "title" => $title, "description" => $desc);
        } else {
            $dynamic_width = '550';
            $dynamic_height = '1000';
            $image_size = @getimagesize($img_url);
            if ($image_size) {
                $dynamic_width = $image_size[0];
                $dynamic_height = $image_size[1];
            }
            $outer = array("url" => $img_url, "id" => strval(rand(1, 999999999)), "width" => $dynamic_width, "height" => $dynamic_height, "thumbnail" => substr($img_url, 0, -4) . "_thumb.jpg", "alt" => "main image", "title" => "post image", "description" => "");
        }
        return $outer;
    }


    static function ats_HasTrailer($mediaType, $mediaValue)
    {
        $mediaTypeArray = explode(",", $mediaType);
        $mediaValueArray = explode(",", $mediaValue);

        $arrayCount = count($mediaTypeArray);
        $outer = array();

        for ($i = 0; $i < $arrayCount; $i++) {
            if ($mediaTypeArray[$i] == "YouTube") {
                $outer[$i + 1] = array("_link" => ('https://www.youtube.com/watch?v=' . $mediaValueArray[$i]));
            } else if ($mediaTypeArray[$i] == "Vimeo") {
                $outer[$i + 1] = array("_link" => ('https://www.vimeo.com/' . $mediaValueArray[$i]));
            }
        }
        return $outer;
    }

    static function ats_SerializeShowTicketsArea($buttonlink, $onSale, $dateTime)
    {
        $buttonlinkArray = explode(",", $buttonlink);
        $onSaleArray = explode(",", $onSale);
        $dateTimeArray = explode(",", $dateTime);
        $arrayCount = count($buttonlinkArray);
        $outer = array();

        for ($i = 0; $i < $arrayCount; $i++) {
            if ($onSaleArray[$i] == "Buy Tickets") {
                $outer[$i + 1] = array("date" => agile_tix_amy_movie_integrate::ats_DateFormat($dateTimeArray[$i]), "hour" => agile_tix_amy_movie_integrate::ats_TimeFormat($dateTimeArray[$i], true), "link" => $buttonlinkArray[$i] . "");
            } else {
                $outer[$i + 1] = array("date" => agile_tix_amy_movie_integrate::ats_DateFormat($dateTimeArray[$i]), "hour" => agile_tix_amy_movie_integrate::ats_TimeFormat($dateTimeArray[$i], true), "link" => $buttonlinkArray[$i] . "");
            }
        }

        return $outer;
    }

    static function ats_DateFormat($datetime)
    {
        return date("Y-m-d", strtotime($datetime));
    }

    static function ats_TimeFormat($datetime, $showtime)
    {
        $time = "";

        if ($showtime == "True")
            $time = date("g:i a", strtotime($datetime));

        return $time;
    }

    function ats_DateTimeFormat($startdatetime, $enddatetime, $showtime, $showenddate)
    {
        $formatted = date("D, M j, Y", strtotime($startdatetime));

        if ($showtime == "True")
            $formatted .= date(" g:i a", strtotime($startdatetime));

        if ($showenddate == "True") {
            $formatted .= " - " . date("D, M j, Y", strtotime($enddatetime));

            if ($showtime == "True")
                $formatted .= date(" g:i a", strtotime($enddatetime));
        }

        return $formatted;
    }

    function ats_ExpireDateTimeFormat($enddatetime)
    {
        return get_gmt_from_date($enddatetime, "Y-m-d H:i");
    }

    function ats_FormatEventSlug($title, $eventid)
    {
        return sanitize_title($title) . "-" . $eventid;
    }

    function ats_SerializeEventVenueValue($venueid)
    {
        $venueArray = array();
        $venueArray[intval($venueid)] = $venueid;
        return serialize($venueArray);
    }

    function ats_SerializeTicketsArea($buttonlink, $buttontext, $title, $subtitle, $style = 0)
    {
        return serialize(array(0, array("title" => $title, "active-style" => "off", "subtitle" => $subtitle, "purchase-type" => "external-link", "event_tickets_package_feature" => "", "woocommerce-product" => "", "quantity" => "default", "price" => "", "eventbrite-link" => "", "meetup-link" => "", "external-link" => $buttonlink . "affid=ticketsnashville&", "contact-form-link" => "", "button-title" => $buttontext, "button-target" => "_self")));
    }

    function ats_SearializeSectionsArea()
    {
        return "a:2:{i:0;a:10:{s:5:\"title\";s:7:\"Tickets\";s:4:\"type\";s:7:\"tickets\";s:24:\"event_extra_tabs_content\";s:0:\"\";s:13:\"speaker-style\";s:7:\"default\";s:14:\"speaker-column\";s:7:\"default\";s:20:\"speaker-column-space\";s:7:\"default\";s:13:\"speaker-photo\";s:7:\"default\";s:18:\"speaker-profession\";s:7:\"default\";s:15:\"speaker-summary\";s:7:\"default\";s:14:\"speaker-social\";s:7:\"default\";}i:1;a:10:{s:5:\"title\";s:3:\"Map\";s:4:\"type\";s:3:\"map\";s:24:\"event_extra_tabs_content\";s:0:\"\";s:13:\"speaker-style\";s:7:\"default\";s:14:\"speaker-column\";s:7:\"default\";s:20:\"speaker-column-space\";s:7:\"default\";s:13:\"speaker-photo\";s:7:\"default\";s:18:\"speaker-profession\";s:7:\"default\";s:15:\"speaker-summary\";s:7:\"default\";s:14:\"speaker-social\";s:7:\"default\";}}";
    }

    function ats_SpecifyCategory($category, $orgid)
    {
        $catString = "";

        if ($category != "orgbased") {
            $catString = $category;
        } else {
            switch ($orgid) {
                case 11878:
                case 12670:
                    $catString = "Cinema";
                    break;
                case 11879:
                    $catString = "Music";
                    break;
                case 11981:
                case 12666:
                    $catString = "Performing Arts";
                    break;
                case 14252:
                    $catString = "Dance";
                    break;
                case 14253:
                    $catString = "Family";
                    break;
                default:
                    $catString = "Other";
                    break;
            }
        }

        return $catString;
    }

    function ats_TagReturns($customPropName, $customPropValue)
    {
        $customPropNameArray = explode(",", $customPropName);
        $customPropValueArray = explode(",", $customPropValue);

        $arrayCount = count($customPropNameArray);
        $outer = "";

        for ($i = 0; $i < $arrayCount; $i++) {
            if (isset($customPropNameArray[$i], $customPropValueArray[$i])) {
                if (strtolower(trim($customPropNameArray[$i])) == "tag") {
                    $outer .= $customPropValueArray[$i] . ",";
                }
            }
        }

        $outer = rtrim($outer, ",");

        return $outer;

    }

    static function groupCustomProperties($data)
    {
        $result = [];

        if (!isset($data['CustomProperties']) || !is_array($data['CustomProperties'])) {
            return $result;
        }

        foreach ($data['CustomProperties'] as $property) {
            $name = $property['Name'];
            $value = $property['Value'];

            if (!isset($result[$name])) {
                $result[$name] = [];
            }

            $result[$name][] = $value;
        }

        // Convert arrays to comma-separated strings
        foreach ($result as $key => $values) {
            $result[$key] = implode(', ', $values);
        }

        return $result;
    }
}
