<?php

class Wpadverts_Mas_Ajax {

    public function __construct() {
        
        add_action( 'wp_ajax_wpadverts_mas', array( $this, "mark_as_sold" ) );
    }
    
    public function mark_as_sold() {
        
        $id = adverts_request("id");
        $is_ajax = adverts_request( "ajax", false );
        $post = get_post($id);
        $result = null;

        // Check AJAX referer
        if( ! check_ajax_referer( 'adverts-mas', '_ajax_nonce', false ) ) {
            $result = array( 
                "result" => 0, 
                "error" => __( "Invalid Session. Please refresh the page and try again.", "wpadverts-mark-as-sold" ) 
            );
        }

        // check if post exists
        if( !$post ) {
            $result = array( 
                "result" => -1, 
                "error" => __( "Post you are trying to modify does not exist.", "wpadverts-mark-as-sold" ) 
            );
        }

        // check if current user is post author
        if( $post->post_author != get_current_user_id() ) {
            $result = array( 
                "result" => -2, 
                "error" => __( "Post you are trying to modify does not belong to you.", "wpadverts-mark-as-sold" ) 
            );
        }

        // check if post is an advert
        if( $post->post_type != 'advert') {
            $result = array( 
                "result" => -3, 
                "error" => __( "This post is not an Advert.", "wpadverts-mark-as-sold" ) 
            );
        }

        if( ! $result === null ) {
            if( $is_ajax ) {
                echo json_encode( $result );
            } else {
                wp_die( $result["error"] );
            }
        }

        do_action( "wpadverts_mark_as_sold_status_change", $id, adverts_request( "mark_as" ) );
        
        if( adverts_request( "mark_as" ) == "sold" ) {
            update_post_meta( $id, Wpadverts_Mas::META, "1" );
        } else {
            delete_post_meta( $id, Wpadverts_Mas::META );
        }
        
        if(adverts_request("redirect_to") ) {
            wp_redirect( adverts_request( "redirect_to" ) );
        } else if( $is_ajax ) {
            echo json_encode( array( 
                "result" => 1, 
                "message" => sprintf( __( "Advert <strong>%s</strong> deleted.", "adverts" ), $post_title )
            ) );
        }

        exit;
    }
}
