<?php

class agile_tix_event_champ_integrate
{

    static function ats_SerializeShowTicketsArea($buttonlink, $buttontext, $title, $subtitle)
    {
        $buttonlinkArray = explode(",", $buttonlink);
        $buttontextArray = explode(",", $buttontext);
        $titleArray = explode(",", $title);
        $subtitleArray = explode(",", $subtitle);

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

        for ($i = 0; $i < $arrayCount; $i++) {
            $outer[$i + 1] = array(
                "title" => agile_tix_event_champ_integrate::ats_DateTimeFormat($titleArray[$i], "", "True", "False"),
                "active-style" => "off",
                "subtitle" => $subtitleArray[$i],
                "purchase-type" => "external-link",
                "event_tickets_package_feature" => "",
                "woocommerce-product" => "",
                "quantity" => "default",
                "price" => "",
                "eventbrite-link" => "",
                "meetup-link" => "",
                "external-link" => $buttonlinkArray[$i] . "",
                "contact-form-link" => "",
                "button-title" => $buttontextArray[$i],
                "button-target" => "agileEmbed"
            );
        }

        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;
    }

    static 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;
    }

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

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

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

    static function ats_SerializeEventVenue($venue)
    {
        $venueArray = array();
        $venueArray[intval($venue['VenueID'])] = $venue['Name'] ?? '';
        return $venueArray;
    }

    static function ats_SerializeTicketsArea($buttonlink, $buttontext, $title, $subtitle, $style = 0)
    {
        return [
            0,
            [
                "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"
            ]
        ];
    }

    static function ats_SearializeSectionsArea()
    {
        return [
            [
                "title" => "Tickets",
                "type" => "tickets",
                "event_extra_tabs_content" => "",
                "speaker-style" => "default",
                "speaker-column" => "default",
                "speaker-column-space" => "default",
                "speaker-photo" => "default",
                "speaker-profession" => "default",
                "speaker-summary" => "default",
                "speaker-social" => "default"
            ],
            [
                "title" => "Map",
                "type" => "map",
                "event_extra_tabs_content" => "",
                "speaker-style" => "default",
                "speaker-column" => "default",
                "speaker-column-space" => "default",
                "speaker-photo" => "default",
                "speaker-profession" => "default",
                "speaker-summary" => "default",
                "speaker-social" => "default"
            ]
        ];
    }

    static 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;
    }

    static 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 ats_TagReturnsFromJson($custom_prop_json)
    {
        $outer = "";

        foreach ($custom_prop_json as $property) {
            if (isset($property['Name']) && strtolower(trim($property['Name'])) == 'tag') {
                if (isset($property['Value'])) {
                    $outer .= trim($property['Value']) . ",";
                }
            }
        }

        // Remove the trailing comma
        return rtrim($outer, ",");
    }



    static function agile_eventChamp_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] : [];
        $firstVenue = isset($firstShowing['Venue']) ? $firstShowing['Venue'] : null;
        $venueLocation = '';
        if ($firstVenue) {
            $Address1 = $firstVenue['Address1'] ?? '';
            $Address2 = $firstVenue['Address2'] ?? '';
            $City = $firstVenue['City'] ?? '';
            $State = $firstVenue['State'] ?? '';
            $Zip = $firstVenue['Zip'] ?? '';
            if ($Address1 != '') {
                $venueLocation .= $Address1 . ', ';
            }
            if ($Address2 != '') {
                $venueLocation .= $Address2 . ', ';
            }
            if ($City != '') {
                $venueLocation .= $City . ', ';
            }
            if ($State != '') {
                $venueLocation .= $State . ', ';
            }
            if ($Zip != '') {
                $venueLocation .= $Zip;
            }
        }

        // Handle empty CurrentShowings (coming soon events never have CurrentShowings)
        $event_start_date = !empty($firstShowing['StartDate']) ? agile_tix_event_champ_integrate::ats_DateFormat($firstShowing['StartDate']) : '';
        $event_start_time = !empty($firstShowing['StartDate']) ? agile_tix_event_champ_integrate::ats_TimeFormat($firstShowing['StartDate'], true) : '';
        $event_end_date = !empty($lastShowing['EndDate']) ? agile_tix_event_champ_integrate::ats_DateFormat($lastShowing['EndDate']) : '';
        $event_end_time = !empty($lastShowing['EndDate']) ? agile_tix_event_champ_integrate::ats_TimeFormat($lastShowing['EndDate'], true) : '';
        $event_expire_date = !empty($lastShowing['EndDate']) ? agile_tix_event_champ_integrate::ats_ExpireDateTimeFormat($lastShowing['EndDate']) : '';
        $event_venue = agile_tix_event_champ_integrate::ats_SerializeEventVenue($firstVenue);
        $event_extra_tabs = agile_tix_event_champ_integrate::ats_SearializeSectionsArea();



        $StringPurchaseLinks = '';
        $StringSalesMessage = '';
        $StringStartDate = '';
        $StringShortDescriptive = '';
        $showingIDs = [];
        foreach ($currentShowings as $show){
            $StringPurchaseLinks .= ($show['LegacyPurchaseLink'] . "," );
            $StringSalesMessage .= ($show['SalesMessage'] . ",");
            $StringStartDate .= ( $show['StartDate'] . "," ) ;
            $StringShortDescriptive .= ( $show['ShortDescriptive']. ",");

            array_push($showingIDs, $show['ID']);
        }
        // Only trim if strings are not empty (coming soon events never have showings)
        if (!empty($StringPurchaseLinks)) {
            $StringPurchaseLinks = substr($StringPurchaseLinks, 0, -1);
        }
        if (!empty($StringSalesMessage)) {
            $StringSalesMessage = substr($StringSalesMessage, 0, -1);
        }
        if (!empty($StringStartDate)) {
            $StringStartDate = substr($StringStartDate, 0, -1);
        }
        if (!empty($StringShortDescriptive)) {
            $StringShortDescriptive = substr($StringShortDescriptive, 0, -1);
        }

        $event_tickets = agile_tix_event_champ_integrate::ats_SerializeShowTicketsArea($StringPurchaseLinks, $StringSalesMessage, $StringStartDate, $StringShortDescriptive);
        
        $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'];
            }
        }

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

        if ($isNewEvent) {
            $postID = wp_insert_post($post_data);
        } else {
            $postID = wp_update_post($post_data);
        }

        $tagValues = array();
        if (!empty($event['CustomProperties'])) {
            $tagValues = agile_tix_event_champ_integrate::ats_TagReturnsFromJson($event['CustomProperties']);
        }

        wp_set_object_terms($postID, $event['CorpOrgName'], 'organizer');
        wp_set_object_terms($postID, $tagValues, 'event_tags');
        wp_set_object_terms($postID, $venueLocation, 'location');
        wp_set_object_terms($postID, $tagValues, 'eventcat');

        //for reasons I can not tell, Event champ meta fields are only registered on update, not on inital creation or update_post
        update_post_meta($postID, 'event_start_date', $event_start_date);
        update_post_meta($postID, 'event_start_time', $event_start_time);
        update_post_meta($postID, 'event_end_date', $event_end_date);
        update_post_meta($postID, 'event_end_time', $event_end_time);
        update_post_meta($postID, 'event_expire_date', $event_expire_date);

        update_post_meta($postID, 'event_extra_tabs', $event_extra_tabs);
        update_post_meta($postID, 'event_tickets', $event_tickets);
        update_post_meta($postID, 'event_detailed_address', $venueLocation);


        $venueQueryArgs = array('post_type' => 'venue', 'p' => $firstVenue['VenueID']);
        $venuePost = get_posts($venueQueryArgs);
        $knownVenue = true;
        if (empty($venuePost)){
            //todo: create venue post
            $knownVenue = false; // temp patch to stop empty venues from being added
        }

        if ($event_venue != '' && $knownVenue) {
            add_post_meta($postID, 'event_venue', $event_venue);
        }
        

        if ($thumbnailID != '') {
            set_post_thumbnail($postID, $thumbnailID);
        }
    }





}
