<?php

namespace AC_SYNC\Includes\Classes\Address {

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

    class Action_Wear_Address
    {
        private static function getTable()
        {
            global $wpdb;
            return $wpdb->prefix . 'actionwear_addresses';
        }

        /**
         * Get all merchant addresses
         *
         * @return array
         */
        public static function getAll()
        {
            global $wpdb;
            $table = self::getTable();
            return $wpdb->get_results("SELECT * FROM $table WHERE type = 'merchant' ORDER BY label ASC", ARRAY_A);
        }

        /**
         * Get a single address by ID
         *
         * @param int $id
         * @return array|null
         */
        public static function getById($id)
        {
            global $wpdb;
            $table = self::getTable();
            return $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $id), ARRAY_A);
        }

        /**
         * Create a new address
         *
         * @param array $data
         * @return int|false Insert ID or false on failure
         */
        public static function create($data)
        {
            global $wpdb;
            $table = self::getTable();

            $fields = self::sanitize($data);
            if (!$fields) {
                return false;
            }

            $result = $wpdb->insert($table, $fields);
            return $result ? $wpdb->insert_id : false;
        }

        /**
         * Update an existing address
         *
         * @param int $id
         * @param array $data
         * @return bool
         */
        public static function update($id, $data)
        {
            global $wpdb;
            $table = self::getTable();

            $fields = self::sanitize($data);
            if (!$fields) {
                return false;
            }

            return $wpdb->update($table, $fields, ['id' => intval($id)]) !== false;
        }

        /**
         * Delete an address
         *
         * @param int $id
         * @return bool
         */
        public static function delete($id)
        {
            global $wpdb;
            $table = self::getTable();
            return $wpdb->delete($table, ['id' => intval($id)]) !== false;
        }

        /**
         * Convert an address record to API destination format
         *
         * @param int $id
         * @return array|null
         */
        public static function toDestinationArray($id)
        {
            $address = self::getById($id);
            if (!$address) {
                return null;
            }

            return [
                'ragione_sociale' => $address['ragione_sociale'],
                'indirizzo' => $address['indirizzo'],
                'localita' => $address['localita'],
                'cap' => $address['cap'],
                'provincia' => $address['provincia'],
                'telefono' => $address['telefono'] ?: '',
                'nazione' => $address['nazione'] ?: 'IT',
                'fermo_deposito' => $address['fermo_deposito'] ?: '',
                'codice_destinazione' => $address['codice_destinazione'] ?: null,
            ];
        }

        /**
         * Update codice_destinazione for an address
         *
         * @param int $id
         * @param string $codice
         * @return bool
         */
        public static function updateCodiceDestinazione($id, $codice)
        {
            global $wpdb;
            $table = self::getTable();
            return $wpdb->update($table, ['codice_destinazione' => $codice], ['id' => intval($id)]) !== false;
        }

        /**
         * Sanitize and validate address data
         *
         * @param array $data
         * @return array|false Sanitized data or false if invalid
         */
        private static function sanitize($data)
        {
            $allowed = [
                'label', 'ragione_sociale', 'indirizzo', 'localita',
                'cap', 'provincia', 'telefono', 'nazione', 'fermo_deposito',
                'codice_destinazione', 'type'
            ];

            $fields = [];
            foreach ($allowed as $key) {
                if (isset($data[$key])) {
                    $fields[$key] = sanitize_text_field($data[$key]);
                }
            }

            // Required fields validation
            $required = ['label', 'ragione_sociale', 'indirizzo', 'localita', 'cap', 'provincia'];
            foreach ($required as $key) {
                if (empty($fields[$key])) {
                    return false;
                }
            }

            // Default type
            if (!isset($fields['type'])) {
                $fields['type'] = 'merchant';
            }

            return $fields;
        }
    }
}
