<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly....
}

global $nele_to_office_key, $nele_to_address_key, $nele_ship_to_key, $nele_place_key, $nele_office_key, $nele_street_key,
       $nele_street_num_key, $nele_district_key, $nele_block_key, $nele_entrance_key, $nele_floor_key, $nele_apt_key, $DELIVERY_OPTS;
$nele_to_office_key  = "to_office";
$nele_to_address_key = "to_address";
$nele_ship_to_key    = 'nele_ship_to';
$nele_state_key      = 'nele_state';
$nele_place_key      = 'nele_place';
$nele_place_id_key   = 'nele_place_id';
$nele_office_key     = 'nele_office';
$nele_office_id_key  = 'nele_office_id';
$nele_street_key     = 'nele_street';
$nele_street_num_key = 'nele_street_num';
$nele_district_key   = 'nele_district';
$nele_block_key      = 'nele_block';
$nele_entrance_key   = 'nele_entrance';
$nele_floor_key      = 'nele_floor';
$nele_apt_key        = 'nele_apt';
$nele_postcode       = 'billing_postcode';

$DELIVERY_OPTS = array(
	$nele_to_office_key => __('To office', 'nextlevel_delivery'),
	$nele_to_address_key => __('To address', 'nextlevel_delivery'));


if (! function_exists('write_to_log_custom')) {

	function write_to_log_custom( $data ) {
		$date = date( "Y-m-d H:i:s: " );
		file_put_contents( 'debug.log', $date . $data . PHP_EOL, FILE_APPEND | LOCK_EX );
	}
}

if (! function_exists('write_log')) {
	function write_log($log) {
		// works only with DEBUG == ON
		if (WP_DEBUG === false) {
			return;
		}

		if (is_array($log) || is_object($log)) {
//			error_log(print_r($log, true));
			write_to_log_custom(print_r($log, true));
		} else {
//			error_log($log);
			write_to_log_custom($log);
		}
	}
}

function nele_add_db_error($error) {
	write_log("Added new error to the nele_errors: $error");
	$errors = nele_get_db_errors();
	$errors[] = $error;
	update_option("nele_errors", $errors);
}

function nele_clear_db_errors() {
	$option_exists = get_option("nele_errors");
	if (! $option_exists) {
		return;
	}
	$result = delete_option("nele_errors");
	if ($result) {
		write_log("Option nele_errors was deleted");
	} else {
		write_log("Option nele_errors was not deleted");
	}
}

function nele_get_db_errors() {
	return get_option("nele_errors", array());
}

function nele_db_to_array($db_rows, $key_field = 'id'): array {
	$result = array();
	foreach ($db_rows as $db_row) {
		$result[] = array('value' => $db_row->$key_field, 'label' => $db_row->name);
	}
	return $result;
}

function nele_binary_to_temp_file($contents)
{
	$file_name = tempnam(sys_get_temp_dir(), "nlo");
	if (is_array($contents)) {
		write_log("nele_binary_to_temp_file: contents is array. Will not write it");
		return null;
	}
	if (file_put_contents($file_name, $contents) === false) {
		write_log("nele_handle_print_labels_action: error writing file contents");
		return null;
	}
	return $file_name;
}

function nele_resolve_parcel_ids_from_orders($order_ids): array
{
	$parcel_ids = array();
	foreach ($order_ids as $order_id) {
        $order = wc_get_order($order_id);
		$parcel_id = $order->get_meta('_nele_created_parcel_id');
		if (empty($parcel_id)) {
			continue;
		}
		$parcel_ids[] = $parcel_id;
	}
	return $parcel_ids;
}

function nele_get_pdf_url($order_id) {
    $order = wc_get_order($order_id);
	return $order->get_meta('_nele_created_pdf_url');
}

function nele_get_parcel_id($order_id) {
    $order = wc_get_order($order_id);
	return $order->get_meta( '_nele_created_parcel_id');
}

function nele_reset_parcel_id($order_id) {
    write_log("nele_reset_parcel_id: .$order_id");
	$parcel_id = nele_get_parcel_id($order_id);
	nele_api_shipment_cancel(nele_parent_obj()->creds, $parcel_id);
    $order = wc_get_order($order_id);
    $order->delete_meta_data('_nele_created_parcel_id');
    $order->delete_meta_data('_nele_shipment_created_at');
	nele_reset_pdf_url($order_id);
}

function nele_reset_pdf_url($order_id) {
	$old_pdf = nele_get_pdf_url($order_id);
	if (file_exists($old_pdf)) {
		unlink($old_pdf);
	}
    $order = wc_get_order($order_id);
    $order->update_meta_data( '_nele_created_pdf_url', '');
    $order->update_meta_data( '_nele_pdf_created_at', '');
    $order->save();
}

function nele_courier_by_shipping_method($shipping_method) {
	$shipping_method_arr = explode( "_", $shipping_method );
	return end( $shipping_method_arr );  # take the last part of string delimited by '_'
}

function nele_shipping_option_key($option, $id, $deliv_opt = null): string {
	$key = $deliv_opt ? $option."_".$id."_".$deliv_opt : $option."_".$id;
//     write_log("nele_shipping_option_key: key=" . $key);
	return $key;
}

function order_date_param_or_default($order_id, $key, $default = 0) {
    $order = wc_get_order($order_id);
	$created_at_str = $order->get_meta($key, true);
	if (empty($created_at_str)) {
		return $default;
	}
	return strtotime($created_at_str);
}

function shipment_created_at($order_id) {
	return order_date_param_or_default($order_id, '_nele_shipment_created_at');
}

function pdf_created_at($order_id) {
	return order_date_param_or_default($order_id, '_nele_pdf_created_at');
}

function nele_shipping_option_value($option, $id, $deliv_opt = null): string {
	return nele_parent_obj()->get_option(nele_shipping_option_key($option, $id, $deliv_opt));
}

function neleGenerateWhereClause(array $conditions): string {
	$where_conditions = array();

	foreach ($conditions as $column => $value) {
		if ($value == null) {
			continue;
		}
		if (str_starts_with($column, "_add")) {
			$where_conditions[] = $value;
			continue;
		}
		$escaped_value = is_numeric($value) ? $value : "'" . esc_sql($value) . "'";
		$where_conditions[] = "{$column} = {$escaped_value}";
	}

	if (! empty($where_conditions)) {
		return "WHERE " . implode(" AND ", $where_conditions);
	}

	return "";
}

class ApiResponse {
	public $msg;
	public bool $is_error;

	public function __construct($msg, $no_die = true, $is_error = false) {
		$this->msg = $msg;
//		write_log("set msg to");
//		write_log($msg);
		$this->is_error = $is_error;
		if ($is_error) {
			write_log($msg);
			if (! $no_die) {
				wp_die($msg);
			}
		}
	}
}

class AddressDetails {
	public bool $ship_to_office = true;
	public ?string $state = null;
	public ?string $place_id = null;
	public ?string $apartment_no = null;
	public ?string $floor_no = null;
	public ?string $entrance_no = null;
	public ?string $block_no = null;
	public ?string $complex = null;
	public ?string $office_id = null;
	public ?string $country = null;
	public ?string $place = null;
	public ?string $street_no = null;
	public ?string $street = null;
	public ?string $post_code = null;
	public ?string $country_id = null;
	public ?string $office = null;

	public function __construct($state = null, $office_id = null, $office = null, $country_id = null, $country = null, $post_code = null, $place_id = null, $place = null, $street = null,
		$street_no = null, $complex = null, $block_no = null, $entrance_no = null, $floor_no = null, $apartment_no = null) {
		$this->state = $state;
		$this->office_id = $office_id;
		$this->office = $office;
		$this->ship_to_office = ! empty($office_id);
		$this->country_id = $country_id;
		$this->country = $country;
		$this->post_code = $post_code;
		$this->place_id = $place_id;
		$this->place = $place;
		$this->street = $street;
		$this->street_no = $street_no;
		$this->complex = $complex;
		$this->block_no = $block_no;
		$this->entrance_no = $entrance_no;
		$this->floor_no = $floor_no;
		$this->apartment_no = $apartment_no;
	}
}

class Parcels {
	public float $price = 0;
	public float $weight = 0;
	public int $count = 0;
	public array $items = array();

	public function add_parcel($p) {
		$this->items[] = $p;
		$this->count += 1;
		$this->weight = round($p->weight+$this->weight,3);
		$this->price = round($this->price+$p->price,2);
	}
}

class Parcel {
	public int $id;
	public float $price;
	public float $weight;
	public float $length;
	public float $width;
	public float $height;
	public function __construct($id, $price, $weight, $length, $width, $height) {
		$this->id = $id;
		$this->price = $price;
		$this->weight = $weight;
		$this->length = $length;
		$this->width = $width;
		$this->height = $height;
	}
}

class OrderStatusSync {
	public bool $is_send;
	public string $status;
	public string $text;

	public function __construct($is_send, $status, $text) {
		$this->is_send = $is_send;
		$this->status = $status;
		$this->text = $text;
	}
}

class ApiCredentials {
	public string $app_id;
	public string $app_secret;
	public string $sender_id;

	public function __construct($app_id, $app_secret, $sender_id) {
		$this->app_id = $app_id;
		$this->app_secret = $app_secret;
		$this->sender_id = $sender_id;
	}
}

class Country {
	public int $id;
	public string $name;
	public string $code;
	public string $currency;

	public function __construct($id, $name, $code, $currency) {
		$this->id = $id;
		$this->name = $name;
		$this->code = $code;
		$this->currency = $currency;
	}
}
