<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Crypto_wallet_model extends CI_Model {

    protected $wallets_table = 'crypto_wallets';
    protected $addresses_table = 'crypto_addresses';

    public function __construct() {
        parent::__construct();
        $this->_migrate();
    }

    /**
     * Create crypto_wallets and crypto_addresses tables if they do not exist.
     */
    protected function _migrate() {
        if ($this->db->table_exists($this->wallets_table)) {
            return;
        }

        $this->db->query("
            CREATE TABLE IF NOT EXISTS `{$this->wallets_table}` (
                `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                `name` VARCHAR(100) NOT NULL COMMENT 'e.g. Bitcoin, Ethereum',
                `symbol` VARCHAR(20) NOT NULL COMMENT 'e.g. BTC, ETH',
                `network` VARCHAR(50) DEFAULT NULL COMMENT 'e.g. ERC-20, Mainnet',
                `instructions` TEXT DEFAULT NULL COMMENT 'Deposit instructions for users',
                `is_active` TINYINT(1) DEFAULT 1,
                `display_order` INT DEFAULT 0,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                INDEX `idx_crypto_wallets_active` (`is_active`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");

        $this->db->query("
            CREATE TABLE IF NOT EXISTS `{$this->addresses_table}` (
                `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                `crypto_wallet_id` INT UNSIGNED NOT NULL,
                `address` VARCHAR(255) NOT NULL COMMENT 'Deposit address',
                `label` VARCHAR(100) DEFAULT NULL COMMENT 'e.g. Primary',
                `is_active` TINYINT(1) DEFAULT 1,
                `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
                `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                FOREIGN KEY (`crypto_wallet_id`) REFERENCES `{$this->wallets_table}`(`id`) ON DELETE CASCADE,
                INDEX `idx_crypto_addresses_wallet` (`crypto_wallet_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
    }

    /**
     * Get wallet by ID
     */
    public function get_wallet($id) {
        return $this->db->get_where($this->wallets_table, ['id' => $id])->row();
    }

    /**
     * Get all wallets (for admin), optionally active only
     */
    public function get_all_wallets($active_only = false) {
        if ($active_only) {
            $this->db->where('is_active', 1);
        }
        $this->db->order_by('display_order', 'ASC');
        $this->db->order_by('name', 'ASC');
        return $this->db->get($this->wallets_table)->result();
    }

    /**
     * Get active wallets with their active addresses (for deposit page)
     */
    public function get_wallets_for_deposit() {
        $wallets = $this->get_all_wallets(true);
        foreach ($wallets as $w) {
            $w->addresses = $this->get_addresses_by_wallet($w->id, true);
        }
        return $wallets;
    }

    /**
     * Get addresses for a wallet
     */
    public function get_addresses_by_wallet($wallet_id, $active_only = false) {
        $this->db->where('crypto_wallet_id', $wallet_id);
        if ($active_only) {
            $this->db->where('is_active', 1);
        }
        $this->db->order_by('id', 'ASC');
        return $this->db->get($this->addresses_table)->result();
    }

    /**
     * Get single address by ID
     */
    public function get_address($id) {
        return $this->db->get_where($this->addresses_table, ['id' => $id])->row();
    }

    /**
     * Create wallet
     */
    public function create_wallet($data) {
        $data['created_at'] = date('Y-m-d H:i:s');
        $this->db->insert($this->wallets_table, $data);
        return $this->db->insert_id();
    }

    /**
     * Update wallet
     */
    public function update_wallet($id, $data) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return $this->db->update($this->wallets_table, $data, ['id' => $id]);
    }

    /**
     * Delete wallet (cascades to addresses)
     */
    public function delete_wallet($id) {
        $this->db->delete($this->addresses_table, ['crypto_wallet_id' => $id]);
        return $this->db->delete($this->wallets_table, ['id' => $id]);
    }

    /**
     * Create address
     */
    public function create_address($data) {
        $data['created_at'] = date('Y-m-d H:i:s');
        $this->db->insert($this->addresses_table, $data);
        return $this->db->insert_id();
    }

    /**
     * Update address
     */
    public function update_address($id, $data) {
        $data['updated_at'] = date('Y-m-d H:i:s');
        return $this->db->update($this->addresses_table, $data, ['id' => $id]);
    }

    /**
     * Delete address
     */
    public function delete_address($id) {
        return $this->db->delete($this->addresses_table, ['id' => $id]);
    }
}
