<?php

require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/BillingHelpers.php';

class BillingPaymentOptionsService
{
    private $pdo;

    public function __construct(PDO $pdo = null)
    {
        $this->pdo = $pdo ?: db();
    }

    public function listPaymentMethods()
    {
        if (!$this->tableExists('billing_payment_methods')) {
            return $this->fallbackPaymentMethods();
        }

        $stmt = $this->pdo->query("\n            SELECT id, method_key, method_name, method_type, is_default, is_active, sort_order\n            FROM billing_payment_methods\n            WHERE is_active = 1\n            ORDER BY sort_order ASC, method_name ASC\n        ");
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
        return $rows ?: $this->fallbackPaymentMethods();
    }

    public function listCashAccounts()
    {
        if (!$this->tableExists('billing_cash_accounts')) {
            return $this->fallbackCashAccounts();
        }

        $stmt = $this->pdo->query("\n            SELECT id, account_key, account_name, account_type, currency_code, bank_name, account_number, is_default, is_active, sort_order\n            FROM billing_cash_accounts\n            WHERE is_active = 1\n            ORDER BY sort_order ASC, account_name ASC\n        ");
        $rows = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : array();
        return $rows ?: $this->fallbackCashAccounts();
    }

    public function getPaymentMethodById($id)
    {
        $id = (int)$id;
        if ($id <= 0 || !$this->tableExists('billing_payment_methods')) {
            return null;
        }
        $stmt = $this->pdo->prepare('SELECT * FROM billing_payment_methods WHERE id = ? AND is_active = 1 LIMIT 1');
        $stmt->execute(array($id));
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    public function getCashAccountById($id)
    {
        $id = (int)$id;
        if ($id <= 0 || !$this->tableExists('billing_cash_accounts')) {
            return null;
        }
        $stmt = $this->pdo->prepare('SELECT * FROM billing_cash_accounts WHERE id = ? AND is_active = 1 LIMIT 1');
        $stmt->execute(array($id));
        return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
    }

    private function tableExists($table)
    {
        static $cache = array();
        $table = preg_replace('/[^a-zA-Z0-9_]/', '', (string)$table);
        if (array_key_exists($table, $cache)) {
            return $cache[$table];
        }
        $stmt = $this->pdo->prepare('SHOW TABLES LIKE ?');
        $stmt->execute(array($table));
        $cache[$table] = (bool)$stmt->fetchColumn();
        return $cache[$table];
    }

    private function fallbackPaymentMethods()
    {
        return array(
            array('id' => 0, 'method_key' => 'transferencia', 'method_name' => 'Transferencia bancaria', 'method_type' => 'bank_transfer', 'is_default' => 1, 'is_active' => 1, 'sort_order' => 10),
            array('id' => 0, 'method_key' => 'efectivo', 'method_name' => 'Efectivo', 'method_type' => 'cash', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 20),
            array('id' => 0, 'method_key' => 'tarjeta_debito', 'method_name' => 'Tarjeta de debito', 'method_type' => 'card', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 30),
            array('id' => 0, 'method_key' => 'tarjeta_credito', 'method_name' => 'Tarjeta de credito', 'method_type' => 'card', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 40),
            array('id' => 0, 'method_key' => 'webpay', 'method_name' => 'Webpay / pasarela de pago', 'method_type' => 'gateway', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 50),
            array('id' => 0, 'method_key' => 'cheque', 'method_name' => 'Cheque', 'method_type' => 'check', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 60),
            array('id' => 0, 'method_key' => 'otro', 'method_name' => 'Otro', 'method_type' => 'other', 'is_default' => 0, 'is_active' => 1, 'sort_order' => 90)
        );
    }

    private function fallbackCashAccounts()
    {
        return array(
            array('id' => 0, 'account_key' => 'banco_cuenta_corriente', 'account_name' => 'Banco / cuenta corriente', 'account_type' => 'bank', 'currency_code' => 'CLP', 'bank_name' => null, 'account_number' => null, 'is_default' => 1, 'is_active' => 1, 'sort_order' => 10),
            array('id' => 0, 'account_key' => 'caja_efectivo', 'account_name' => 'Caja efectivo', 'account_type' => 'cash', 'currency_code' => 'CLP', 'bank_name' => null, 'account_number' => null, 'is_default' => 0, 'is_active' => 1, 'sort_order' => 20),
            array('id' => 0, 'account_key' => 'pasarela_webpay', 'account_name' => 'Pasarela Webpay', 'account_type' => 'gateway', 'currency_code' => 'CLP', 'bank_name' => null, 'account_number' => null, 'is_default' => 0, 'is_active' => 1, 'sort_order' => 30),
            array('id' => 0, 'account_key' => 'otra_cuenta', 'account_name' => 'Otra cuenta/caja', 'account_type' => 'other', 'currency_code' => 'CLP', 'bank_name' => null, 'account_number' => null, 'is_default' => 0, 'is_active' => 1, 'sort_order' => 90)
        );
    }
}
