<?php
/**
 * ICYLAB OS - Directorio unificado de proveedores.
 *
 * Los proveedores reutilizan crm_customers como contraparte maestra para evitar
 * duplicados de RUT y conservar la trazabilidad entre clientes, DTE y cobranza.
 */
require_once __DIR__ . '/../../core/database.php';

class SupplierDirectoryService
{
    private $pdo;

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

    public function listSuppliers($search = '', $status = '')
    {
        $where = array(
            's.deleted_at IS NULL',
            "(s.is_supplier = 1 OR s.counterparty_type IN ('supplier','both'))"
        );
        $params = array();

        $search = trim((string)$search);
        if ($search !== '') {
            $where[] = "(s.customer_name LIKE ? OR s.commercial_name LIKE ? OR s.legal_name LIKE ? OR s.customer_tax_id LIKE ? OR s.email LIKE ? OR s.contact_name LIKE ?)";
            $like = '%' . $search . '%';
            for ($i = 0; $i < 6; $i++) $params[] = $like;
        }

        $status = strtolower(trim((string)$status));
        if (in_array($status, array('active', 'inactive', 'blocked'), true)) {
            $where[] = 's.supplier_status = ?';
            $params[] = $status;
        }

        $sql = "
            SELECT
                s.*,
                COALESCE(fc_supplier.center_name, fc_default.center_name) AS cost_center_name,
                fc_income.center_name AS income_center_name,
                pt.term_label AS supplier_payment_term_label,
                COALESCE(stats.documents_count, 0) AS documents_count,
                COALESCE(stats.open_documents, 0) AS open_documents,
                COALESCE(stats.open_balance, 0) AS open_balance,
                stats.last_document_date
            FROM crm_customers s
            LEFT JOIN finance_centers fc_supplier ON fc_supplier.id = s.supplier_default_cost_center_id
            LEFT JOIN finance_centers fc_default ON fc_default.id = s.default_cost_center_id
            LEFT JOIN finance_centers fc_income ON fc_income.id = s.default_income_center_id
            LEFT JOIN billing_payment_terms pt ON pt.id = s.supplier_payment_terms_id
            LEFT JOIN (
                SELECT
                    d.supplier_customer_id,
                    COUNT(*) AS documents_count,
                    SUM(CASE WHEN COALESCE(c.collection_status, d.payment_status, 'por_pagar') IN ('por_pagar','vencido','parcial') THEN 1 ELSE 0 END) AS open_documents,
                    SUM(CASE
                        WHEN COALESCE(c.collection_status, d.payment_status, 'por_pagar') IN ('por_pagar','vencido','parcial')
                        THEN CASE WHEN c.id IS NULL THEN d.total_amount ELSE GREATEST(c.balance_amount, 0) END
                        ELSE 0
                    END) AS open_balance,
                    MAX(COALESCE(d.document_date, DATE(d.receive_date))) AS last_document_date
                FROM facto_inbox_documents d
                LEFT JOIN billing_collections c
                    ON c.direction = 'payable'
                    AND c.environment = d.environment
                    AND c.inbox_document_id = d.inbox_document_id
                WHERE d.supplier_customer_id IS NOT NULL
                GROUP BY d.supplier_customer_id
            ) stats ON stats.supplier_customer_id = s.id
            WHERE " . implode(' AND ', $where) . "
            ORDER BY COALESCE(s.commercial_name, s.customer_name) ASC
        ";

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function getSupplier($supplierId)
    {
        $stmt = $this->pdo->prepare("
            SELECT
                s.*,
                COALESCE(fc_supplier.center_name, fc_default.center_name) AS cost_center_name,
                fc_income.center_name AS income_center_name,
                pt.term_label AS supplier_payment_term_label,
                pt.days AS supplier_payment_term_days
            FROM crm_customers s
            LEFT JOIN finance_centers fc_supplier ON fc_supplier.id = s.supplier_default_cost_center_id
            LEFT JOIN finance_centers fc_default ON fc_default.id = s.default_cost_center_id
            LEFT JOIN finance_centers fc_income ON fc_income.id = s.default_income_center_id
            LEFT JOIN billing_payment_terms pt ON pt.id = s.supplier_payment_terms_id
            WHERE s.id = ?
              AND s.deleted_at IS NULL
              AND (s.is_supplier = 1 OR s.counterparty_type IN ('supplier','both'))
            LIMIT 1
        ");
        $stmt->execute(array((int)$supplierId));
        $supplier = $stmt->fetch(PDO::FETCH_ASSOC);
        return $supplier ?: null;
    }

    public function getDocuments($supplierId, $limit = 100)
    {
        $limit = max(1, min(250, (int)$limit));
        $stmt = $this->pdo->prepare("
            SELECT
                d.id,
                d.environment,
                d.document_type_taxbureau,
                d.document_number,
                d.document_date,
                d.payment_due_date,
                d.total_amount,
                COALESCE(c.paid_amount, 0) AS paid_amount,
                CASE WHEN c.id IS NULL THEN d.total_amount ELSE GREATEST(c.balance_amount, 0) END AS balance_amount,
                COALESCE(c.collection_status, d.payment_status, 'por_pagar') AS payment_status,
                COALESCE(fc_doc.center_name, fc_supplier.center_name, fc_default.center_name) AS finance_center_name,
                d.pdf_file_path,
                d.xml_file_path
            FROM facto_inbox_documents d
            LEFT JOIN billing_collections c
                ON c.direction = 'payable'
                AND c.environment = d.environment
                AND c.inbox_document_id = d.inbox_document_id
            LEFT JOIN crm_customers s ON s.id = d.supplier_customer_id
            LEFT JOIN finance_centers fc_doc ON fc_doc.id = d.finance_center_id
            LEFT JOIN finance_centers fc_supplier ON fc_supplier.id = s.supplier_default_cost_center_id
            LEFT JOIN finance_centers fc_default ON fc_default.id = s.default_cost_center_id
            WHERE d.supplier_customer_id = ?
            ORDER BY COALESCE(d.document_date, DATE(d.receive_date)) DESC, d.id DESC
            LIMIT " . $limit
        );
        $stmt->execute(array((int)$supplierId));
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function summarizeDocuments(array $documents)
    {
        $summary = array(
            'documents' => count($documents),
            'total' => 0.0,
            'paid' => 0.0,
            'open_balance' => 0.0,
            'overdue' => 0
        );
        foreach ($documents as $document) {
            $summary['total'] += (float)($document['total_amount'] ?? 0);
            $summary['paid'] += (float)($document['paid_amount'] ?? 0);
            $summary['open_balance'] += (float)($document['balance_amount'] ?? 0);
            if (in_array((string)($document['payment_status'] ?? ''), array('vencido'), true)) $summary['overdue']++;
        }
        return $summary;
    }
}
