<?php

if ( ! defined( 'ABSPATH' ) ) {
	return;
}

add_action( 'giveasap_metabox_object_giveasap_text', 'giveasap_free_metabox_text' );

$metabox_general = new GiveASAP_Metabox( 'General', 'giveasap_general', array( 'giveasap' ), 'advanced', 'high', '<i class="fal fa-gift"></i>' );

$metabox = new GiveASAP_Metabox( 'Scheduling', 'giveasap_schedule', array( 'giveasap' ), 'advanced', 'high', '<i class="fal fa-calendar"></i>' );

$metabox_prize = new GiveASAP_Metabox( 'Prize Info', 'giveasap_prize', array( 'giveasap' ), 'advanced', 'high', '<i class="fal fa-trophy-alt"></i>' );

$metabox_display = new GiveASAP_Metabox( 'Display', 'giveasap_display', array( 'giveasap' ), 'side', 'high', '<i class="fal fa-crop"></i>' );

$metabox_text = new GiveASAP_Metabox( 'Text & Email', 'giveasap_text', array( 'giveasap' ), 'side', 'high', '<i class="fal fa-pencil-alt"></i>' );

$metabox_scripts = new GiveASAP_Metabox( 'Scripts', 'giveasap_scripts', array( 'giveasap' ), 'side', 'high', '<i class="fal fa-code"></i>' );

add_action( 'gasap_metabox_giveasap_schedule_before_fields', 'gasap_schedule_text' );
function gasap_schedule_text() {
	echo '<p> ' . __( 'The Date will be formatted on the front end with the format that is set in Settings > General.', 'giveasap' ) . '</p>';
	echo '<p>' . __( 'The format used here is Day-Month-Year', 'giveasap' ) . '</p>';
}

$timeArray = array();

for ( $i = 0; $i < 24; $i++ ) {
	$hour = $i;
	if ( $hour < 10 ) {
		$hour = '0' . $hour;
	}

	for ( $j = 0; $j < 4; $j++ ) {

		$minute = '00';

		if ( $j == 1 ) {
			$minute = '15';
		}

		if ( $j == 2 ) {
			$minute = '30';
		}

		if ( $j == 3 ) {
			$minute = '45';
		}

		$timeArray[ $hour . ':' . $minute ] = $hour . ':' . $minute;
	}
}

$today    = date( 'd-m-Y' );
$tomorrow = date( 'd-m-Y', strtotime( 'Tomorrow' ) );

$metabox_general->add_field(
	array(
		'id'      => 'giveasap_type',
		'name'    => 'giveasap_type',
		'title'   => __( 'Type', 'giveasap' ),
		'type'    => 'select',
		'options' => giveasap_get_giveaway_types(),
		'sync_key' => 'type',
		'builder_adapter' => 'select',
		'single'  => true, // Save it as a single post meta.
	)
);

$metabox_general->add_field(
	array(
		'id'    => 'sg_limit',
		'name'  => 'sg_limit',
		'title' => __( 'Limit', 'giveasap' ),
		'type'  => 'text',
		'class' => array( 'hide_if_any', 'show_if_limited', 'hide_if_simple', 'hide_if_logged_in', 'hide_if_no_subscriber_page', 'hide_if_evergreen' ),
		'desc'  => __( 'Limit this giveaway by the number of subscribers. Entries not important.', 'giveasap' ),
        'sync_key' => 'sg_limit',
	)
);

$metabox_general->add_field(
	array(
		'id'    => 'sg_login_url',
		'name'  => 'sg_login_url',
		'title' => __( 'Login URL', 'giveasap' ),
		'type'  => 'text',
		'class' => array( 'hide_if_any', 'show_if_logged_in' ),
		'desc'  => __( 'Enter where the login form is if a visitor wants to enter the giveaway.', 'giveasap' ),
        'sync_key' => 'sg_login_url',
	)
);

$metabox_general->add_field(
	array(
		'id'    => 'sg_registration_url',
		'name'  => 'sg_registration_url',
		'title' => __( 'Registration URL', 'giveasap' ),
		'type'  => 'text',
		'class' => array( 'hide_if_any', 'show_if_logged_in' ),
		'desc'  => __( 'Enter where the registration form is if a visitor wants to enter the giveaway.', 'giveasap' ),
        'sync_key' => 'sg_registration_url',
	)
);

$metabox_general->add_field(
	array(
		'id'    => 'sg_redirect',
		'name'  => 'sg_redirect',
		'title' => __( 'Redirect', 'giveasap' ),
		'type'  => 'text',
		'desc'  => __( 'Add the link where the subscriber will be redirected. If left empty, it will use the giveaway page. If you are using a different page and want the giveaway to show, please be sure to add the correct shortcode/block. The Activation Link will still point towards the default Giveaway page.', 'giveasap' ),
        'sync_key' => 'sg_redirect',
	)
);

$metabox_general->add_field(
	array(
		'id'    => 'sg_giveaway_page',
		'name'  => 'sg_giveaway_page',
		'title' => __( 'Main Giveaway Page', 'giveasap' ),
		'type'  => 'text',
		'sync_key' => 'giveaway_page',
		'builder_adapter' => 'url',
		'desc'  => __( 'Add the link where the giveaway is showing. If left empty, it will use the default giveaway page. This can be useful if you are using a shortcode/block to link to that page from emails.', 'giveasap' ),
        'sync_key' => 'sg_giveaway_page',
	)
);

$metabox->add_field(
	array(
		'id'      => 'giveasap_start_date',
		'name'    => 'start_date',
		'title'   => __( 'Start Date', 'giveasap' ),
		'type'    => 'datetime',
		'default' => $today,
        'sync_key' => 'giveasap_start_date',
	)
);

$metabox->add_field(
	array(
		'id'      => 'giveasap_start_time',
		'name'    => 'start_time',
		'title'   => __( 'Start Time', 'giveasap' ),
		'type'    => 'select',
		'options' => $timeArray,
		'default' => '00:00',
        'sync_key' => 'giveasap_start_time',
	)
);

$metabox->add_field(
	array(
		'id'      => 'giveasap_end_date',
		'name'    => 'end_date',
		'title'   => __( 'End Date', 'giveasap' ),
		'type'    => 'datetime',
		'default' => $tomorrow,
        'sync_key' => 'giveasap_end_date',
	)
);

$metabox->add_field(
	array(
		'id'      => 'giveasap_end_time',
		'name'    => 'end_time',
		'title'   => __( 'End Time', 'giveasap' ),
		'type'    => 'select',
		'options' => $timeArray,
		'default' => '00:00',
        'sync_key' => 'giveasap_end_time',
	)
);

$metabox->add_field(
	array(
		'id'      => 'giveasap_winner_date',
		'name'    => 'winner_date',
		'title'   => __( 'Winner Announcement Date', 'giveasap' ),
		'type'    => 'datetime',
		'class'   => array( 'show_if_any', 'hide_if_evergreen' ),
		'default' => $tomorrow,
        'sync_key' => 'giveasap_winner_date',
	)
);

$metabox->add_field(
	array(
		'name'  => 'sg_hide_timezone',
		'title' => __( 'Hide Timezone?', 'giveasap' ),
		'type'  => 'checkbox',
		'desc'  => __(
			'If checked, Timezone will not be shown in giveaway dates.',
			'giveasap'
		),
        'sync_key' => 'sg_hide_timezone',
	)
);


$metabox->add_field(
	array(
		'id'      => 'giveasap_winner_time',
		'name'    => 'winner_time',
		'title'   => __( 'Winner Announcement Time', 'giveasap' ),
		'type'    => 'select',
		'class'   => array( 'show_if_any', 'hide_if_evergreen' ),
		'options' => $timeArray,
		'default' => '00:00',
        'sync_key' => 'giveasap_winner_time',
	)
);

$metabox->add_field(
	array(
		'id'      => 'remind_days_before',
		'name'    => 'remind_days_before',
		'title'   => __( 'Remind subscribers (days)', 'giveasap' ),
		'type'    => 'text',
		'class'   => array( 'show_if_any', 'hide_if_evergreen' ),
		'desc'    => __( 'Remind subscribers a few days before the end of the giveaway. Leave 0 to not remind. Example: add 1 to remind users 1 day before the end.', 'giveasap' ),
		'default' => '0',
        'sync_key' => 'remind_days_before',
	)
);

$metabox_prize->add_field(
	array(
		'name'    => 'winner_threshold',
		'default' => '100',
		'title'   => __( 'Winner Threshold', 'giveasap' ),
		'desc'    => __( 'How many entries does a subscriber has to get to win the prize.', 'giveasap' ),
		'class'   => array( 'hide_if_any', 'show_if_evergreen' ),
        'sync_key' => 'winner_threshold',
	)
);

$metabox_prize->add_field(
	array(
		'name'    => 'type',
		'type'    => 'select',
		'default' => 'default',
		'title'   => __( 'Type', 'giveasap' ),
		'desc'    => __( 'How are the winners selected', 'giveasap' ),
		'options' => array(
			'default'   => __( 'Most Entries win', 'giveasap' ),
			'random'    => __( 'Entries only give a higher chance of winning', 'giveasap' ),
			'threshold' => __( 'Prizes are won when their entry points are met', 'giveasap' ),
			//'spend'  => __( 'Prizes are won by spending entries for them', 'giveasap' ),
		),
		'class'   => array( 'show_if_any', 'hide_if_limited', 'hide_if_evergreen', 'hide_if_instant', 'hide_if_ticket' ),
        'sync_key' => 'prize_type',
	)
);

$metabox_prize->add_field(
	array(
		'name'    => 'winners',
		'type'    => 'text',
		'default' => 1,
		'builder_adapter' => 'number',
		'title'   => __( 'Number of winners', 'giveasap' ),
		'desc'    => __( 'How many winners can be selected', 'giveasap' ),
		'class'   => array( 'show_if_any', 'hide_if_instant' ),
        'sync_key' => 'prize_winners',
	)
);

/**
 * @param \GiveASAP_Metabox $metabox_text
 */
function giveasap_free_metabox_text( $metabox_text ) {

	$metabox_text->add_field(
		array(
			'name'    => 'rules_sponsor',
			'title'   => __( 'Rules: Sponsor(s)', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'Sponsor(s) of the giveaway. If you don\'t have any, remove or change sentences with {{sponsor_name}}',
			'default' => '',
            'sync_key' => 'giveasap_free_sponsor',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'rules_sponsor_address',
			'title'   => __( 'Rules: Sponsor(s) Address', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'Sponsor(s) address of the giveaway. If you don\'t have any, remove or change sentences with {{sponsor_address}}',
			'default' => '',
            'sync_key' => 'giveasap_free_sponsor_address',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'rules_sponsor_email',
			'title'   => __( 'Rules: Sponsor Email(s)', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'Sponsor email(s) of the giveaway. If you don\'t have any, remove or change sentences with {{sponsor_email}}',
			'default' => '',
            'sync_key' => 'giveasap_free_sponsor_email',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'rules_sponsor_country',
			'title'   => __( 'Rules: Sponsor Country', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'Sponsor country or countries. If you don\'t have any, remove or change sentences with {{sponsor_country}}',
			'default' => '',
            'sync_key' => 'giveasap_free_sponsor_country',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'rules_eligible_locations',
			'title'   => __( 'Rules: Eligible Location(s)', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'If you don\'t have any, remove or change sentences with {{eligible_locations}}',
			'default' => '',
            'sync_key' => 'giveasap_free_eligible_locations',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'eligible_min_age',
			'title'   => __( 'Rules: Eligible Min. Age', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'If you don\'t have any, remove or change sentences with {{eligible_min_age}}',
			'default' => '',
            'sync_key' => 'giveasap_free_eligible_min_age',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'rules_text',
			'title'   => __( 'Rules', 'giveasap' ),
			'type'    => 'wpeditor',
			'desc'    => __( 'Rules will show at the bottom. Placeholders: {{giveaway_name}} - Giveaway Title, {{start_date}} - start date, {{end_date}} - end date, {{sponsor_name}} - Sponsor Name, {{sponsor_email}} - Sponsor Email, {{eligible_locations}} - Eligible Locations, {{eligible_min_age}} - Eligible min. age, {{giveaway_url}} - Giveaway URL, {{sponsor_country}} - Sponsor Country, {{sponsor_address}} - Sponsor Address', 'giveasap' ),
			'default' => __(
				"<p>NO PURCHASE NECESSARY TO ENTER OR WIN. MAKING A PURCHASE OR PAYMENT OF ANY KIND WILL NOT INCREASE YOUR CHANCES OF WINNING. VOID WHERE PROHIBITED OR RESTRICTED BY LAW.</p>
                      <p>PROMOTION DESCRIPTION: The {{giveaway_name}} ('Sweepstakes') begins on {{start_date}} and ends on {{end_date}} (the 'Promotion Period').</p>

<p>The sponsor of this Sweepstakes is {{sponsor_name}} ('Sponsor'). By participating in the Sweepstakes, each Entrant unconditionally accepts and agrees to comply with and abide by these Official Rules and the decisions of Sponsor, which shall be final and binding in all respects. Sponsor is responsible for the collection, submission or processing of Entries and the overall administration of the Sweepstakes. Entrants should look solely to Sponsor with any questions, comments or problems related to the Sweepstakes. Sponsor may be reached by email at {{sponsor_email}} during the Promotion Period.</p>

<p>ELIGIBILITY: Open to legal residents of {{eligible_locations}} who are {{eligible_min_age}} (the 'Entrant'). Sponsor, and their respective parents, subsidiaries, affiliates, distributors, retailers, sales representatives, advertising and promotion agencies and each of their respective officers, directors and employees (the 'Promotion Entities'), are ineligible to enter the Sweepstakes or win a prize. Household Members and Immediate Family Members of such individuals are also not eligible to enter or win. 'Household Members' shall mean those people who share the same residence at least three months a year. 'Immediate Family Members' shall mean parents, step-parents, legal guardians, children, step-children, siblings, step-siblings, or spouses. This Sweepstakes is subject to all applicable federal, state and local laws and regulations and is void where prohibited or restricted by law.</p>

<p>HOW TO ENTER: Enter the Sweepstakes during the Promotion Period online by visiting the entry form, which can be found on the following website at {{giveaway_url}}. Automated or robotic Entries submitted by individuals or organizations will be disqualified. Internet entry must be made by the Entrant. Any attempt by Entrant to obtain more than the stated number of Entries by using multiple/different email addresses, identities, registrations, logins or any other methods, including, but not limited to, commercial contest/sweepstakes subscription notification and/or entering services, will void Entrant's Entries and that Entrant may be disqualified. Final eligibility for the award of any prize is subject to eligibility verification as set forth below. All Entries must be posted by the end of the Promotion Period in order to participate. Sponsor's database clock will be the official timekeeper for this Sweepstakes.</p>
    
<p>WINNER SELECTION: The Winner(s) of the Sweepstakes will be selected in a random drawing from among all eligible Entries received throughout the Promotion Period. The random drawing will be conducted within about 7 days after the Promotion Period by Sponsor or its designated representatives, whose decisions are final. Odds of winning will vary depending on the number of eligible Entries received.</p>

<p>WINNER NOTIFICATION: Winner will be notified by email at the email address provided in the Entry Information approximately within 7 days after the random drawing. Potential Winner must accept a prize by email as directed by Sponsor within 7 days of notification. Sponsor is not responsible for any delay or failure to receive notification for any reason, including inactive email account(s), technical difficulties associated therewith, or Winner’s failure to adequately monitor any email account.</p>

<p>Any winner notification not responded to or returned as undeliverable may result in prize forfeiture. The potential prize winner may be required to sign and return an affidavit of eligibility and release of liability, and a Publicity Release (collectively 'the Prize Claim Documents'). No substitution or transfer of a prize is permitted except by Sponsor.</p>

<p>PRIVACY: Any personal information supplied by you will be subject to the privacy policy of the Sponsor posted on the Sponsor's website. By entering the Sweepstakes, you grant Sponsor permission to share your email address and any other personally identifiable information.</p>

<p>LIMITATION of LIABILITY: By entering, You agree to release and hold harmless {{sponsor_name}} and its subsidiaries, affiliates, advertising and promotion agencies, partners, representatives, agents, successors, assigns, employees, officers, and directors from any liability, illness, injury, death, loss, litigation, claim, or damage that may occur, directly or indirectly, whether caused by negligence or not, from: (i) such entrant’s participation in the Sweepstakes and/or his/her acceptance, possession, use, or misuse of any prize or any portion thereof; (ii) technical failures of any kind, including but not limited to the malfunction of any computer, cable, network, hardware, or software, or other mechanical equipment; (iii) the unavailability or inaccessibility of any transmissions, telephone, or Internet service; (iv) unauthorized human intervention in any part of the entry process or the Promotion; (v) electronic or human error in the administration of the Promotion or the processing of entries.</p>

<p>DISPUTES: This Sweepstakes IS GOVERNED BY THE LAWS OF {{sponsor_country}}, WITHOUT RESPECT TO CONFLICT OF LAW DOCTRINES. As a condition of participating in this Sweepstakes, participant agrees that any and all disputes that cannot be resolved between the parties, and causes of action arising out of or connected with this Sweepstakes, shall be resolved individually, without resort to any form of class action. Further, in any such dispute, under no circumstances shall participant be permitted to obtain awards for, and hereby waives all rights to, punitive, incidental, or consequential damages, including reasonable attorney’s fees. Participant further waives all rights to have damages multiplied or increased.</p>

<p>WINNER LIST: To obtain a copy of the Winner List, send your request along with a stamped, self-addressed envelope to {{sponsor_name}} cc: {{giveaway_name}} at {{sponsor_address}}. Requests for the names of the winners must be received no later than 30 days after the Promotion Period has ended.</p>

<p>SPONSOR: {{sponsor_name}}, {{sponsor_address}}, {{sponsor_email}}</p>",
				'giveasap'
			),
            'sync_key' => 'giveasap_free_rules_text',
		)
	);

	/**
	 * Adding Winner Subject
	 *
	 * @since  2.6.2
	 */
	$metabox_text->add_field(
		array(
			'name'    => 'winner_subject',
			'title'   => __( 'Winner Subject', 'giveasap' ),
			'type'    => 'text',
			'desc'    => 'Subject for the winner email. {{TITLE}} - placeholder for prize name<br/>For form fields use field key as FIELD_KEY in {{FORM_FIELD_KEY}}. Example: field key phone_number, to display it, use {{FORM_PHONE_NUMBER}}',
			'default' => 'Congratulations, you have won {{TITLE}}',
            'sync_key' => 'giveasap_free_winner_subject',
		)
	);

	$metabox_text->add_field(
		array(
			'name'    => 'winner_email',
			'title'   => __( 'Winner Email', 'giveasap' ),
			'type'    => 'wpeditor',
			'desc'    => 'This text will be sent to the winner(s). {{TITLE}} - placeholder for prize name<br/>For form fields use field key as FIELD_KEY in {{FORM_FIELD_KEY}}. Example: field key phone_number, to display it, use {{FORM_PHONE_NUMBER}}.<br/>For Prize instructions use {{PRIZE_INSTRUCTIONS}}',
			'default' => 'Congratulations, <br/> you have won {{TITLE}}',
            'sync_key' => 'giveasap_free_winner_email',
		)
	);

}

$metabox_prize->add_field(
	array(
		'name'        => 'prize',
		'title'       => __( 'Prize', 'giveasap' ),
		'type'        => 'text',
		'sync_key'    => 'prize_name',
		'builder_adapter' => 'text',
		'desc'        => 'Enter the name of the prize (example: Product Title)',
		'placeholder' => __(
			'1 year Subscription Plan',
			'giveasap'
		),
	)
);

$metabox_prize->add_field(
	array(
		'name'        => 'value',
		'title'       => __( 'Value', 'giveasap' ),
		'type'        => 'text',
		'sync_key'    => 'prize_value',
		'builder_adapter' => 'text',
		'desc'        => 'Enter the value of the prize (example: $1,000.00)',
		'placeholder' => __(
			'$100.00',
			'giveasap'
		),
	)
);

$metabox_prize->add_field(
	array(
		'name'    => 'prizes',
		'title'   => __( 'Prizes', 'giveasap' ),
		'type'    => 'custom',
		'desc'    => 'Enter the value of the prize (example: $1,000.00)',
		'render'  => 'giveasap_prizes_metabox_field',
        'validate' => 'giveasap_prizes_metabox_field_validate',
		'default' => array(),
	)
);

function giveasap_prizes_metabox_field_validate( $data ) {
    if ( ! $data ) {
        return $data;
    }

    foreach ( $data as $index => $prize_fields ) {
        $data[ $index ]['title'] = sanitize_text_field( $prize_fields['title'] );
    }

    return $data;
}

$metabox_prize->add_field(
	array(
		'name'    => 'show_instructions',
		'title'   => __( 'Show Prize Instructions', 'giveasap' ),
		'type'    => 'checkbox',
		'desc'    => 'If checked, the winner will see the prize instructions on the giveaway page.',
		'default' => 'no',
        'sync_key' => 'giveasap_free_show_instructions',
	)
);

$metabox_prize->add_field(
	array(
		'name'    => 'prizes_layout',
		'title'   => __( 'Prizes Layout', 'giveasap' ),
		'type'    => 'radio',
		'sync_key' => 'prizes_layout',
		'builder_adapter' => 'radio',
		'desc'    => 'How should prizes be shown',
		'options' => array(
			'slider'   => __( 'Slider', 'giveasap' ),
			'vertical' => __( 'Vertical', 'giveasap' ),
		),
		'default' => 'slider',
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'page_layout',
		'title' => __( 'Page Layout?', 'giveasap' ),
		'type'  => 'checkbox',
		'sync_key' => 'page_layout',
		'builder_adapter' => 'checkbox',
		'builder_transform' => 'page_layout_checkbox_enum',
		'desc'  => __(
			'If checked, header and footer of your site will be displayed also.',
			'giveasap'
		),
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'logo',
		'title' => __( 'Logo', 'giveasap' ),
		'type'  => 'image',
		'sync_key' => 'logo',
		'builder_adapter' => 'image',
		'desc'  => __(
			'Logo of the sponsor, you or the prize',
			'giveasap'
		),
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'logo_link',
		'title' => __( 'Logo Link', 'giveasap' ),
		'type'  => 'text',
		'sync_key' => 'logo_link',
		'builder_adapter' => 'url',
		'desc'  => __(
			'Where will the logo link to? Leave empty for no link',
			'giveasap'
		),
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'images',
		'title' => __( 'Images', 'giveasap' ),
		'type'  => 'gallery',
		'desc'  => 'Add images and order their display. First image will be used as share images if those are not defined below',
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'background_color',
		'title' => __( 'Background Color', 'giveasap' ),
		'type'  => 'color',
		'sync_key' => 'background_color',
		'builder_adapter' => 'color',
		'desc'  => 'This color is used when there is no Background Image',
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'background_image',
		'title' => __( 'Background Image', 'giveasap' ),
		'type'  => 'image',
		'sync_key' => 'background_image',
		'builder_adapter' => 'image',
		'desc'  => 'This image is used as a background image on the giveaway landing page',
	)
);


$metabox_display->add_field(
	array(
		'name'  => 'pinterest_image',
		'title' => __( 'Pinterest Image', 'giveasap' ),
		'type'  => 'image',
		'desc'  => 'This image will be used when people pin this giveaway',
        'sync_key' => 'pinterest_image',
        'builder_adapter' => 'image',
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'facebook_image',
		'title' => __( 'Facebook Image', 'giveasap' ),
		'type'  => 'image',
		'desc'  => 'This image will be used when people share this giveaway on Facebook',
        'sync_key' => 'facebook_image',
        'builder_adapter' => 'image',
	)
);

$metabox_display->add_field(
	array(
		'name'  => 'twitter_image',
		'title' => __( 'X Image', 'giveasap' ),
		'type'  => 'image',
		'desc'  => 'This image will be used when people share this giveaway on X (Twitter)',
        'sync_key' => 'twitter_image',
        'builder_adapter' => 'image',
	)
);


$metabox_display->add_field(
	array(
		'name'    => 'twitter_account',
		'title'   => __( 'X Account', 'giveasap' ),
		'type'    => 'text',
		'desc'    => 'X (Twitter) account (with @) to be applied in meta',
		'default' => '@wpgiveaways',
        'sync_key' => 'twitter_account',
	)
);

$metabox_scripts->add_field(
    array(
        'name'    => 'scripts',
        'title'   => __( 'Scripts', 'giveasap' ),
        'type'    => 'code',
        'desc'    => 'Scripts that will load on the giveaway page',
        'sync_key' => 'giveasap_free_scripts',
    )
);

$metabox_scripts->add_field(
    array(
        'name'    => 'visitor_scripts',
        'title'   => __( 'Visitor Scripts', 'giveasap' ),
        'type'    => 'code',
        'desc'    => 'Scripts that will load on the giveaway page for people who are not signed up.',
        'sync_key' => 'giveasap_free_visitor_scripts',
    )
);

$metabox_scripts->add_field(
    array(
        'name'    => 'subscriber_scripts',
        'title'   => __( 'Subscribed Scripts', 'giveasap' ),
        'type'    => 'code',
        'desc'    => 'Scripts that will load on the giveaway page for people who are signed up.',
        'sync_key' => 'giveasap_free_subscriber_scripts',
    )
);

/**
 * Field Values
 *
 * @param $field
 */
function giveasap_prizes_metabox_field( $field ) {
	$fields    = isset( $field['default'] ) && is_array( $field['default'] ) ? $field['default'] : array();
	$is_visual = isset( $field['_render_context'] ) && 'visual' === $field['_render_context'];
	$id_suffix  = $is_visual ? '-vb' : '';
	$add_btn_id = $is_visual ? 'sgAddPrizesFieldVisual' : 'sgAddPrizesField';

	if ( $is_visual ) { ?>
		<div class="giveasap-field-group">
			<label><?php esc_html_e( 'Prizes', 'giveasap' ); ?></label>
	<?php } else { ?>
		<tr>
			<th><?php esc_html_e( 'Prizes', 'giveasap' ); ?></th>
			<td>
	<?php } ?>

		<div class="sg-prizes-field-container" data-giveasap-sync-key="prizes_repeater" data-giveasap-adapter="repeater">
			<?php
			foreach ( $fields as $index => $form_field ) {
				$title     = isset( $form_field['title'] ) ? esc_html( $form_field['title'] ) : '';
				$value     = isset( $form_field['value'] ) ? $form_field['value'] : '';
				$image     = isset( $form_field['image'] ) ? $form_field['image'] : 0;
				$desc      = isset( $form_field['desc'] ) ? $form_field['desc'] : '';
				$threshold = isset( $form_field['threshold'] ) ? $form_field['threshold'] : '';

				$field_name = $title ? $title : __( 'Prize Name', 'giveasap' );
				$img_id     = 'sg-field-image-' . $index . $id_suffix;
				?>

				<div class="sg-form-field" data-index="<?php echo esc_attr( $index ); ?>">
					<div class="sg-form-field-header">
						<div class="handle-column">
							<div class="sg-form-row-handle"><i class="fal fa-sort"></i></div>
						</div>
						<div class="sg-field-name">
							<?php echo esc_html( $field_name ); ?>
						</div>
					</div>
					<div class="sg-form-field-body">
						<table class="form-table sg-form-table">
							<tr class="sg-field-name">
								<th>
									<label for="sg-field-name-<?php echo esc_attr( $index . $id_suffix ); ?>"><?php esc_html_e( 'Title', 'giveasap' ); ?></label>
								</th>
								<td>
									<input id="sg-field-name-<?php echo esc_attr( $index . $id_suffix ); ?>" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][title]" value="<?php echo esc_attr( $title ); ?>" placeholder="<?php esc_attr_e( 'Prize Name', 'giveasap' ); ?>" />
								</td>
							</tr>
							<tr class="sg-field-value">
								<th>
									<label for="sg-field-value-<?php echo esc_attr( $index . $id_suffix ); ?>"><?php esc_html_e( 'Value', 'giveasap' ); ?></label>
								</th>
								<td>
									<input id="sg-field-value-<?php echo esc_attr( $index . $id_suffix ); ?>" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][value]" value="<?php echo esc_attr( $value ); ?>" placeholder="$100.00" />
								</td>
							</tr>
							<tr class="sg-field-desc">
								<th>
									<label for="sg-field-desc-<?php echo esc_attr( $index . $id_suffix ); ?>"><?php esc_html_e( 'Description', 'giveasap' ); ?></label>
								</th>
								<td>
									<textarea class="sg-field-desc-textarea" id="sg-field-desc-<?php echo esc_attr( $index . $id_suffix ); ?>" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][desc]"><?php echo esc_attr( $desc ); ?></textarea>
								</td>
							</tr>
							<tr class="sg-field-image">
								<th>
									<label for="<?php echo esc_attr( $img_id ); ?>"><?php esc_html_e( 'Image', 'giveasap' ); ?></label>
								</th>
								<td>
									<ul id="<?php echo esc_attr( $img_id ); ?>" class="sortable_wordpress_gallery">
										<?php
										$gallery = explode( ',', $image );
										if ( count( $gallery ) > 0 && $gallery[0] ) {
											foreach ( $gallery as $attachment_id ) {
												?>
												<li tabindex="0" role="checkbox" aria-label="<?php echo esc_attr( get_the_title( $attachment_id ) ); ?>" aria-checked="true" data-id="<?php echo esc_attr( $attachment_id ); ?>" class="attachment save-ready selected details">
													<div class="attachment-preview js--select-attachment type-image subtype-jpeg portrait">
														<div class="thumbnail">
															<div class="centered">
																<img src="<?php echo esc_url_raw( wp_get_attachment_thumb_url( $attachment_id ) ); ?>" draggable="false" alt="">
															</div>
														</div>
													</div>
													<button type="button" data-gallery="#<?php echo esc_attr( $img_id ); ?>" class="button-link check remove-sortable-wordpress-gallery-image" tabindex="0">
														<span class="media-modal-icon"></span>
														<span class="screen-reader-text"><?php esc_html_e( 'Deselect', 'giveasap' ); ?></span>
													</button>
												</li>
												<?php
											}
										}
										?>
									</ul>
									<input type="hidden" id="<?php echo esc_attr( $img_id ); ?>_input" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][image]" value="<?php echo esc_attr( $image ); ?>" />
									<button type="button" class="button button-primary add-single-wordpress-image" data-gallery="#<?php echo esc_attr( $img_id ); ?>"><?php esc_html_e( 'Add Image', 'giveasap' ); ?></button>
								</td>
							</tr>

							<tr class="sg-prize-field-threshold show_if_any hide_if_instant hide_if_ticket">
								<th>
									<label for="sg-prizes-field-threshold-<?php echo esc_attr( $index . $id_suffix ); ?>"><?php esc_html_e( 'Threshold', 'giveasap' ); ?></label>
								</th>
								<td>
									<input id="sg-prizes-field-threshold-<?php echo esc_attr( $index . $id_suffix ); ?>" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[<?php echo esc_attr( $index ); ?>][threshold]" value="<?php echo esc_attr( $threshold ); ?>" placeholder="Threshold" />
									<p class="description"><?php esc_html_e( 'Enter the number of entries needed for winning this prize. Getting to this threshold automatically awards the prize.', 'giveasap' ); ?></p>
								</td>
							</tr>

							<?php do_action( 'sg_prizes_field_table_tbody_columns', $form_field, $index, $field ); ?>

							<tr>
								<th colspan="2">
									<?php
									if ( ! isset( $form_field['readonly'] ) || ! $form_field['readonly'] ) {
										?>
										<button type="button" class="button button-secondary sg-delete-prizes-field"><?php esc_html_e( 'Delete Field' ); ?></button>
										<?php
									}
									do_action( 'sg_prizes_field_table_tbody_column_actions', $form_field, $index, $field );
									?>
								</th>
							</tr>
						</table>
					</div>
				</div>
				<?php
			}
			?>
			</div>
			<button type="button" id="<?php echo esc_attr( $add_btn_id ); ?>" class="button button-secondary"><?php esc_html_e( 'Add Prize', 'giveasap' ); ?></button>

			<script type="text/template" id="tmpl-sg-prizes-field">
				<div class="sg-form-field" data-index="{{ data.index }}">
					<div class="sg-form-field-header">
						<div class="handle-column">
							<div class="sg-form-row-handle"><i class="fal fa-sort"></i></div>
						</div>
						<div class="sg-field-name">
							<?php
							esc_html_e( 'Field Name', 'giveasap' );
							?>
						</div>
					</div>
					<div class="sg-form-field-body">
						<table class="form-table sg-form-table">
							<tr class="sg-field-name">
								<th>
									<label for="sg-field-name-{{ data.index }}"><?php esc_html_e( 'Title', 'giveasap' ); ?></label>
								</th>
								<td>
									<input id="sg-field-name-{{ data.index }}" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][title]" value="" placeholder="<?php esc_html_e( 'Field Name', 'giveasap' ); ?>" />
								</td>
							</tr>
							<tr class="sg-field-value">
								<th>
									<label for="sg-field-value-{{ data.index }}"><?php esc_html_e( 'Value', 'giveasap' ); ?></label>
								</th>
								<td>
									<input id="sg-field-value-{{ data.index }}" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][value]" value="" placeholder="$100.00" />
								</td>
							</tr>
							<tr class="sg-field-desc">
								<th>
									<label for="sg-field-desc-{{ data.index }}"><?php esc_html_e( 'Description', 'giveasap' ); ?></label>
								</th>
								<td>
									<textarea class="sg-field-desc-textarea" id="sg-field-key-{{ data.index }}" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][desc]"></textarea>
								</td>
							</tr>
							<tr class="sg-field-image">
								<th>
									<label for="sg-field-image-{{ data.index }}"><?php esc_html_e( 'Image', 'giveasap' ); ?></label>
								</th>
								<td>
									<ul id="sg-field-image-{{ data.index }}-vb" class="sortable_wordpress_gallery"></ul>
									<!-- Hidden input used to save the gallery image IDs into the database -->
									<!-- We are also creating dynamic IDs here so that we can easily target them in JavaScript -->
									<input type="hidden" id="sg-field-image-{{ data.index }}-vb_input" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][image]" value="" />
									<!-- Button used to open the WordPress Media Library Modal -->
									<button type="button" class="button button-primary add-single-wordpress-image" data-gallery="#sg-field-image-{{ data.index }}-vb"><?php esc_html_e( 'Add Image', 'giveasap' ); ?></button>
								</td>
							</tr>

                            <tr class="sg-prize-field-threshold show_if_any hide_if_instant hide_if_ticket">
                                <th>
                                    <label for="sg-prizes-field-threshold-{{ data.index }}"><?php esc_html_e( 'Threshold', 'giveasap' ); ?></label>
                                </th>
                                <td>
                                    <input id="sg-prizes-field-threshold-{{ data.index }}" type="text" name="<?php echo esc_attr( $field['name'] ); ?>[{{ data.index }}][threshold]" value="" placeholder="Threshold"" />
                                    <p class="description"><?php esc_html_e( 'Enter the number of entries needed for winning this prize. Getting to this threshold automatically awards the prize.', 'giveasap' ); ?></p>
                                </td>
                            </tr>


							<?php do_action( 'sg_prizes_field_table_tbody_columns', array(), '{{ data.index }}', $field ); ?>

							<tr>
								<td colspan="2">

									<button type="button" class="button button-secondary sg-delete-prizes-field"><?php esc_html_e( 'Delete Field' ); ?></button>

									<?php
									do_action( 'sg_prizes_field_table_tbody_column_actions', array(), '{{ data.index }}', $field );
									?>
								</td>
							</tr>
						</table>
					</div>
				</div>

			</script>

	<?php if ( $is_visual ) { ?>
		</div>
	<?php } else { ?>
		</td>
		</tr>
	<?php } ?>
<?php
}

$metaboxes = new GiveASAP_Metaboxes();
$metaboxes->add( $metabox_general );
$metaboxes->add( $metabox );
$metaboxes->add( $metabox_prize );
$metaboxes->add( $metabox_display );
$metaboxes->add( $metabox_text );
$metaboxes->add( $metabox_scripts );
$metaboxes->register();
