<?php

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

if (! class_exists('INTEGRAZO_WZ_Account_Model')) {

    class INTEGRAZO_WZ_Account_Model
    {
        private $wpdb;
        private $table_name;

        public function __construct()
        {
            global $wpdb;
            $this->wpdb = $wpdb;
            $this->table_name = $wpdb->prefix . 'integrazo_wz_accounts';
        }

        /**
         * Add new account with data.
         *
         * @param string $account_name
         * @param string $account_data (should be JSON or serialized data)
         * @return int|false Inserted ID on success, false on failure
         */
        public function add_account($account_name, $product_name, $account_data, $input_data, $data_center = null)
        {
            $current_user_id = get_current_user_id();

            $data = [
                'account_name' => $account_name,
                'product_name' => $product_name,
                'account_data' => maybe_serialize($account_data),
                'input_data'   => maybe_serialize($input_data),
                'created_by'   => $current_user_id,
                'updated_by'   => $current_user_id,
                'created_at'   => current_time('mysql'),
                'updated_at'   => current_time('mysql'),
            ];

            if (!is_null($data_center)) {
                $data['data_center'] = $data_center;
            }

            $result = $this->wpdb->insert($this->table_name, $data);

            return $result ? $this->wpdb->insert_id : false;
        }

        /**
         * Update account name, account_data, input_data, and data_center by account ID.
         *
         * @param int    $id
         * @param string $account_name
         * @param array  $account_data
         * @param array  $input_data
         * @param string $data_center
         * @return bool True on success, false on failure
         */
        public function update_account_by_id($id, $account_name, $account_data, $input_data, $data_center = null)
        {
            if (!is_numeric($id)) {
                return false;
            }

            $current_user_id = get_current_user_id();

            $data = [
                'account_name' => $account_name,
                'account_data' => maybe_serialize($account_data),
                'input_data'   => maybe_serialize($input_data),
                'updated_by'   => $current_user_id,
                'updated_at'   => current_time('mysql'),
            ];

            if (!is_null($data_center)) {
                $data['data_center'] = $data_center;
            }

            $result = $this->wpdb->update(
                $this->table_name,
                $data,
                ['id' => $id],
                null,  // let wpdb auto-detect formats
                ['%d']
            );

            return $result !== false;
        }


        /**
         * Get account by ID.
         *
         * @param int $id
         * @return array|null
         */
        public function get_account_by_id($id)
        {
            if (! is_numeric($id)) {
                return null;
            }

            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching	
            $row = $wpdb->get_row(
                $wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    "SELECT * FROM {$this->table_name} WHERE id = %d",
                    $id
                ),
                ARRAY_A
            );

            if ($row) {
                $row['account_data'] = maybe_unserialize($row['account_data']);
            }

            return $row;
        }

        /**
         * Get total number of accounts.
         *
         * @return int
         */
        public function get_total_accounts_count()
        {
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $count = $this->wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}");
            return (int) $count;
        }
        /**
         * Get all accounts for a specific product name.
         *
         * @param string $product_name
         * @return array List of account records
         */
        public function get_accounts_by_product_name($product_name)
        {
            if (empty($product_name)) {
                return [];
            }

            global $wpdb;
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching	
            $results = $wpdb->get_results(
                $wpdb->prepare(
                    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    "SELECT * FROM {$this->table_name} WHERE product_name = %s",
                    $product_name
                ),
                ARRAY_A
            );

            // Unserialize account_data for each record
            foreach ($results as &$row) {
                $row['account_data'] = maybe_unserialize($row['account_data']);
            }

            return $results;
        }
        public function get_account_data()
        {
            global $wpdb, $blog_id;

            // Fetch all account data from the database
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            $data = $wpdb->get_results("SELECT * FROM " . esc_sql($this->table_name), ARRAY_A);

            if (is_wp_error($data) || empty($data)) {
                // Handle errors or return an empty array if no data is found
                return [];
            }


            return $data;
        }
        // Function to get the total number of accounts
        public function get_total_accounts()
        {
            global $wpdb;
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            return $wpdb->get_var("SELECT COUNT(*) FROM {$this->table_name}");
        }
        // Delete an error log by ID
        public function delete_error_log($id)
        {
            return $this->wpdb->delete(
                $this->table_name,
                ['id' => $id],
                ['%d']
            ) !== false;
        }
        /**
         * Get product name by account ID.
         *
         * @param int $id
         * @return string|null
         */
        public function get_product_name_by_id($id)
        {
            if (!is_numeric($id)) {
                return null;
            }

            global $wpdb;

            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.InterpolatedNotPrepared
            $product_name = $wpdb->get_var(
                $wpdb->prepare(
                    "SELECT product_name FROM `" . esc_sql($this->table_name) . "` WHERE id = %d",
                    $id
                )
            );

            return $product_name;
        }
    }
}
