<?php

namespace Elex\MultiVendor\Model;

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

use Elex\MultiVendor\Model\Store;

class Vendor { 

	const META_KEY = 'elex_vendor_data';

	public $vendor;

	public $vendor_attributes = array();


	public function __construct() {
	}

	public static function default_values() {
	
		return array(

			'store_id'          => '',
			'store_url'         => '',
			'store_full_addr1'  => '',
			'store_full_addr2'  => '',
			'city'              => '',
			'state'             => '',
			'postal'            => '',
			'country'           => '',
			'paypal_email'      => '',
			'phone_number'      => '',
			'is_setup_finished' => false,        
		);
	}

	public function has_store() {
		$args = array(
			'post_type' => 'elex_vendor',
		);

		$args['author']      = isset( $this->vendor->ID ) ? $this->vendor->ID : '';
		$args['post_status'] = array( 'pending', 'publish', 'draft', 'reject' );

		$author_posts = get_posts( $args );

		if ( 0 === count( $author_posts ) ) {
			return false;
		}
		return true;
	}

	public function had_store() {
		$args = array(
			'post_type' => 'elex_vendor',
		);

		$args['author']      = isset( $this->vendor->ID ) ? $this->vendor->ID : '';
		$args['post_status'] = array( 'private' );

		$author_posts = get_posts( $args );

		if ( 0 === count( $author_posts ) ) {
			return false;
		}
		return true;
	}

	public static function is_vendor() {
		$user = wp_get_current_user();

		if ( in_array( 'elex_mv_vendor', (array) $user->roles ) ) {
			return true;
		} else {
			return;
		}       
	}


	public function get_store() {

		$store = Store::load_by_vendor( $this );

		return $store;
	}

	public function get_id() {
		if ( is_object( $this->vendor ) ) {
			return $this->vendor->ID;
		}
	}

	public function update_store() {
	}

	public static function load( $vendor ) {
	
		$self = new self();
		$self->set_vendor( $vendor );
		$self->load_attributes();
		return $self;
	}
	
	public function load_attributes() {
		
		if ( is_object( $this->vendor ) ) {

			$this->vendor_attributes = get_user_meta( $this->vendor->ID, self::META_KEY, true );
			if ( ! $this->vendor_attributes ) {
				$this->vendor_attributes = self::default_values();
			}
			self::save();
		}
	}
	


	public function save() {
		if ( is_object( $this->vendor ) ) {
			$returned_update = update_user_meta( $this->vendor->ID, 'elex_vendor_data', $this->vendor_attributes );
			return $returned_update ;
		}
	}


	public function get_vendor() {
		return $this->vendor;
	}

	public function set_vendor( $vendor ) {
		$this->vendor = $vendor;
	}

	public function get( $key ) {
		$this->load_attributes();

		if ( isset( $this->vendor_attributes[ $key ] ) ) {
		
			return $this->vendor_attributes[ $key ];
		}
		return null;
	}

	public function set( $key, $value ) {
		$this->vendor_attributes[ $key ] = $value;
	}

	public function is_setup_finished() {
		return $this->get( 'is_setup_finished' );
	}
}
