<?php
/**
 * PaymentAccount Model
 * Maps to `payment_accounts` table — Admin-managed receiving accounts
 */

require_once __DIR__ . '/../Core/Model.php';

class PaymentAccount extends Model {
    protected string $table = 'payment_accounts';

    public function getActiveAccounts(): array {
        $sql = "SELECT pa.*, pa.account_no as account_number, pa.type as method, pa.is_primary as is_default
                FROM `payment_accounts` pa
                WHERE pa.is_active = 1
                ORDER BY pa.type ASC, pa.is_primary DESC, pa.created_at ASC";
        return $this->fetchAll($sql);
    }

    public function getAllAccounts(): array {
        $sql = "SELECT pa.*, pa.account_no as account_number, pa.type as method, pa.is_primary as is_default
                FROM `payment_accounts` pa
                ORDER BY pa.type ASC, pa.is_primary DESC, pa.is_active DESC, pa.created_at ASC";
        return $this->fetchAll($sql);
    }

    public function getActiveByMethod(string $method): ?array {
        $cleanType = strtolower(str_replace(' ', '', $method));
        if ($cleanType === 'banktransfer') {
            $cleanType = 'bank';
        }

        $sql = "SELECT pa.*, pa.account_no as account_number, pa.type as method, pa.is_primary as is_default
                FROM `payment_accounts` pa
                WHERE (pa.type = :type OR pa.type = :raw) AND pa.is_active = 1 AND pa.is_primary = 1
                LIMIT 1";
        $result = $this->fetchOne($sql, [':type' => $cleanType, ':raw' => $method]);

        // Fallback to any active account for this type
        if (!$result) {
            $sql = "SELECT pa.*, pa.account_no as account_number, pa.type as method, pa.is_primary as is_default
                    FROM `payment_accounts` pa
                    WHERE (pa.type = :type OR pa.type = :raw) AND pa.is_active = 1
                    ORDER BY pa.created_at ASC LIMIT 1";
            $result = $this->fetchOne($sql, [':type' => $cleanType, ':raw' => $method]);
        }

        return $result;
    }

    /**
     * Set default account for a given method, un-setting previous default
     */
    public function setDefault(int $id, string $method): bool {
        $cleanType = strtolower(str_replace(' ', '', $method));
        if ($cleanType === 'banktransfer') {
            $cleanType = 'bank';
        }

        $this->db->beginTransaction();
        try {
            // Unset all defaults for this method
            $sql = "UPDATE `payment_accounts` SET `is_primary` = 0
                    WHERE `type` = :type OR `type` = :raw";
            $this->db->prepare($sql)->execute([':type' => $cleanType, ':raw' => $method]);

            // Set new default
            $sql = "UPDATE `payment_accounts` SET `is_primary` = 1, `updated_at` = NOW()
                    WHERE `id` = :id";
            $this->db->prepare($sql)->execute([':id' => $id]);

            $this->db->commit();
            return true;
        } catch (Exception $e) {
            $this->db->rollBack();
            throw $e;
        }
    }

    public function toggleActive(int $id, int $updatedBy): bool {
        $sql = "UPDATE `payment_accounts`
                SET `is_active` = IF(`is_active` = 1, 0, 1),
                    `updated_at` = NOW()
                WHERE `id` = :id";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }
}
