<?php

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

/**
 * Class Realia_Import
 *
 * @class Realia_Import
 * @package Realia/Classes
 * @author Pragmatic Mates
 */
class Realia_Import {
    /**
     * Initialize import
     *
     * @access public
     * @return void
     */
    public static function init() {
	    add_action( 'admin_menu', array( __CLASS__, 'import_menu' ) );
	    add_action( 'init', array( __CLASS__, 'import_process' ), 9999 );
    }

    /**
     * Create import menu item
     *
     * @access public
     * @return void
     */
    public static function import_menu() {
	    if ( current_theme_supports( 'realia-import' ) ) {
		    add_submenu_page( 'edit.php?post_type=property', __( 'CSV Import', 'realia' ), __( 'CSV Import', 'realia' ), 'manage_options', 'import', array(
			    __CLASS__,
			    'import'
		    ) );
	    }
    }

    /**
     * Import template
     *
     * @access public
     * @return void
     */
    public static function import() {
        echo Realia_Template_Loader::load( 'misc/import' );
    }

    /**
     * Start importing
     *
     * @access public
     * @return void
     */
    public static function import_process() {
        global $wpdb;

        if ( ! array_key_exists( 'import-form', $_POST ) ) {
            return;
        }

        $_SESSION['import_messages'] = array();

        // Fix for Mac OS CSV file endings
        ini_set( 'auto_detect_line_endings', true );

        // No file uploaded
        if ( empty( $_FILES['file'] ) ) {
            $_SESSION['import_messages'][] = __( 'No file selected.', 'realia' );
            return;
        }

        // Check the file extension
        if ( $_FILES['file']['type']  != 'text/csv' ) {
            $_SESSION['import_messages'][] = __( 'This is not CSV file.', 'realia' );
            return;
        }

        $handler = fopen( $_FILES['file']['tmp_name'], 'r' );
        $index = 0;

        while ( ! feof( $handler ) ) {
            $row = fgetcsv( $handler, 1024 );

            // Create new post type
            $post_id = wp_insert_post( array(
                'post_type' 	=> 'property',
                'post_status' 	=> 'publish',
                'post_title' 	=> ! empty( $row[0] ) ? $row[0] : '',
                'post_content' 	=> ! empty( $row[1] ) ? $row[1] : '',
            ) );

            // Add featured image
            $filename = $row[2];
            if ( ! empty( $filename ) ) {
                $attachment_id = self::import_attachment( $filename, $post_id );
                add_post_meta( $post_id, '_thumbnail_id', $attachment_id );
            }

            // Locations
            self::import_terms( $row[3], $post_id, 'locations' );

            // Types
            self::import_terms( $row[4], $post_id, 'property_types' );

            // Contracts
            self::import_terms( $row[5], $post_id, 'contracts' );

            // Amenities
            self::import_terms( $row[6], $post_id, 'amenities' );

            // ID
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'id', $row[7] );

            // Latitude
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'map_location_latitude', $row[8] );

            // Longitude
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'map_location_longitude', $row[9] );
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'map_location',  array(
                'latitude' => $row[8],
                'longitude' => $row[9],
            ) );

            // Price
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'price', $row[10] );

            // Baths
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'attributes_baths', $row[11] );

            // Beds
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'attributes_beds', $row[12] );

            // Garages
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'attributes_garages', $row[13] );

            // Area
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'attributes_area', $row[14] );

            // Gallery
            $images = explode(' ', $row[15] );
            $gallery = array();
            foreach ( $images as $image ) {
                $attachment_id = self::import_attachment( $image, $post_id );
                $gallery[$attachment_id] = wp_get_attachment_url( $attachment_id );
            }
            self::import_field( $post_id, REALIA_PROPERTY_PREFIX . 'gallery', $gallery );

            $index++;
        }

        $_SESSION['import_status'][] = sprintf( __( '%s properties has been successfully imported.', 'realia' ), $index );

        fclose( $handler );
    }

    /**
     * Loads image from external source
     *
     * @access public
     * @param $filename
     * @param $post_id
     * @return int
     */
    public static function import_attachment( $filename, $post_id ) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';

        $is_external = false;

        // If the image path is starting with http we are gonna to download it
        if (substr( $filename, 0, 4 ) === 'http') {
            $is_external = true;

            $image_id = Realia_Utilities::media_sideload_image( $filename, $post_id );
            $image = wp_get_attachment_image_src( $image_id, 'full' );
        }

        $filetype = wp_check_filetype( basename( $filename ), null );
        $wp_upload_dir = wp_upload_dir();
        $args = array(
            'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ),
            'post_mime_type' => $filetype['type'],
            'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
            'post_content'   => '',
            'post_status'    => 'inherit'
        );

        if ( $is_external )	{
            $args['guid'] = $image[0];
            $attachment_id = wp_insert_attachment( $args, get_attached_file( $image_id )  , $post_id );
            $attachment_data = wp_generate_attachment_metadata( $attachment_id, get_attached_file( $image_id ) );
        } else {
            $attachment_id = wp_insert_attachment( $args, $filename , $post_id );
            $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
        }

        wp_update_attachment_metadata( $attachment_id, $attachment_data );

        return $attachment_id;
    }

    /**
     * Saves regular fields
     *
     * @access public
     * @param $post_id
     * @param $key
     * @param $value
     * @return bool
     */
    public static function import_field( $post_id, $key, $value ) {
        if ( ! empty( $value ) ) {
            update_post_meta( $post_id, $key, $value );
            return true;
        }

        return false;
    }

    /**
     * Imports terms
     *
     * @access public
     * @param $terms
     * @param $post_id
     * @param $taxonomy
     * @return bool
     */
    public static function import_terms( $terms, $post_id, $taxonomy) {
        $parsed_terms = explode( ', ', $terms );
        $term_ids = array();

        if ( empty( $terms ) ) {
            return false;
        }

        foreach ( $parsed_terms as $term ) {
            $term = trim( $term );
            $existing_term = get_term_by( 'slug', sanitize_title( $term ), $taxonomy );

            if ( empty( $existing_term ) ) {
                $term_id = wp_insert_term( $term, $taxonomy );
            } else {
                $term_id = $existing_term->term_id;
            }

            $term_ids[] = $term_id;
        }

        wp_set_post_terms( $post_id, $term_ids, $taxonomy );
        return true;
    }
}

Realia_Import::init();