<?php
session_start();
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/modules/shared/helpers.php';
require_once BASE_PATH . '/database/connection.php';

if (!isset($_SESSION['client_id'])) { header('Location: ' . module_url('client_portal/login.php')); exit(); }

$page_title = 'Transacciones';
$module = 'transactions';
$action = 'list';

$clientId = (int)$_SESSION['client_id'];
$db = Database::getInstance();
$pdo = $db->getConnection();

// Asegurar columnas opcionales para compatibilidad
try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN payment_method VARCHAR(64) NULL"); } catch (Throwable $__) {}
try { $pdo->exec("ALTER TABLE payment_attempts ADD COLUMN channel VARCHAR(32) NULL"); } catch (Throwable $__) {}

// Incluir depósitos manuales registrados desde CRM
try { $pdo->query("SELECT 1 FROM client_deposits LIMIT 1"); $hasClientDeposits = true; } catch (Throwable $__) { $hasClientDeposits = false; }

if ($hasClientDeposits) {
    $sql = "SELECT
                CAST(method AS CHAR(32)) COLLATE utf8mb4_general_ci AS method,
                CAST(identifier AS CHAR(64)) COLLATE utf8mb4_general_ci AS identifier,
                amount,
                CAST(currency AS CHAR(16)) COLLATE utf8mb4_general_ci AS currency,
                CAST(status AS CHAR(32)) COLLATE utf8mb4_general_ci AS status,
                CAST(payment_method AS CHAR(64)) COLLATE utf8mb4_general_ci AS payment_method,
                CAST(channel AS CHAR(32)) COLLATE utf8mb4_general_ci AS channel,
                created_at,
                updated_at
            FROM payment_attempts WHERE client_id = ?
            UNION ALL
            SELECT CAST('manual' AS CHAR(32)) COLLATE utf8mb4_general_ci AS method,
                   CAST(CONCAT('MD-', cd.id) AS CHAR(64)) COLLATE utf8mb4_general_ci AS identifier,
                   cd.amount AS amount,
                   CAST(cd.currency AS CHAR(16)) COLLATE utf8mb4_general_ci AS currency,
                   CAST(COALESCE(cd.status,'confirmed') AS CHAR(32)) COLLATE utf8mb4_general_ci AS status,
                   CAST(COALESCE(cd.method,'manual') AS CHAR(64)) COLLATE utf8mb4_general_ci AS payment_method,
                   CAST('cash' AS CHAR(32)) COLLATE utf8mb4_general_ci AS channel,
                   cd.created_at AS created_at,
                   NULL AS updated_at
            FROM client_deposits cd WHERE cd.client_id = ?
            ORDER BY created_at DESC LIMIT 200";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$clientId, $clientId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} else {
    $stmt = $pdo->prepare("SELECT method, identifier, amount, currency, status, payment_method, channel, created_at, updated_at FROM payment_attempts WHERE client_id = ? ORDER BY id DESC LIMIT 200");
    $stmt->execute([$clientId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

ob_start();
?>
    <div class="section-header">
        <h2 class="section-title"><i class="fas fa-arrows-left-right"></i> Transacciones de Depósito</h2>
        <div class="section-actions">
            <button class="client-action-btn" id="txRefreshBtn"><i class="fas fa-rotate"></i> Actualizar</button>
        </div>
    </div>

    <section class="support-card">
        <div class="table-responsive">
            <table class="table table-striped premium" id="txTable">
                <colgroup>
                    <col class="col-date" />
                    <col class="col-order" />
                    <col class="col-provider" />
                    <col class="col-method" />
                    <col class="col-channel" />
                    <col class="col-amount" />
                    <col class="col-status" />
                </colgroup>
                <thead>
                    <tr>
                        <th>Fecha</th>
                        <th>Order ID</th>
                        <th>Proveedor</th>
                        <th>Payment Method</th>
                        <th>Channel</th>
                        <th>Monto (USD)</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $r): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($r['created_at']); ?></td>
                        <td><?php echo htmlspecialchars($r['identifier']); ?></td>
                        <td><?php echo strtoupper(htmlspecialchars($r['method'])); ?></td>
                        <td><span class="chip pm"><?php echo htmlspecialchars($r['payment_method'] ?? ''); ?></span></td>
                        <td><span class="chip channel <?php echo strtolower($r['channel'] ?? '')==='cash'?'cash':'online'; ?>"><?php echo strtoupper(htmlspecialchars($r['channel'] ?? '')); ?></span></td>
                        <td><?php echo number_format((float)$r['amount'], 2); ?></td>
                        <td><span class="badge status <?php $st=strtolower($r['status']); echo ($st==='paid'||$st==='approved'||$st==='success')?'ok':(($st==='failed'||$st==='cancelled')?'bad':'warn'); ?>"><?php echo strtoupper(htmlspecialchars($r['status'])); ?></span></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </section>
    <script>
    (function(){
      const btn = document.getElementById('txRefreshBtn');
      const tbody = document.querySelector('#txTable tbody');
      function refresh(){ location.reload(); }
      if (btn) btn.addEventListener('click', refresh);
    })();
    </script>
    <style>
      .table.premium{border:1px solid #e5e7eb;border-radius:12px;overflow:hidden;table-layout:fixed;width:100%}
      .table.premium thead th{background:#f6f8fb;font-weight:700}
      .table.premium th,.table.premium td{padding:10px 12px;vertical-align:middle}
      .table.premium thead th:nth-child(1), .table.premium tbody td:nth-child(1){text-align:left;font-weight:700}
      .table.premium thead th:nth-child(2), .table.premium tbody td:nth-child(2){text-align:left;font-weight:700}
      .table.premium thead th:nth-child(3), .table.premium tbody td:nth-child(3){text-align:left;font-weight:700}
      .table.premium thead th:nth-child(4), .table.premium tbody td:nth-child(4){text-align:center}
      .table.premium thead th:nth-child(5), .table.premium tbody td:nth-child(5){text-align:center}
      .table.premium thead th:nth-child(6), .table.premium tbody td:nth-child(6){text-align:right;font-weight:700}
      .table.premium thead th:nth-child(7), .table.premium tbody td:nth-child(7){text-align:center}
      .table.premium col{width:14.285%}
      .badge.status{display:inline-flex;align-items:center;justify-content:center;padding:4px 8px;border-radius:999px;font-weight:700;min-width:88px}
      .badge.status.ok{background:#dcfce7;color:#166534}
      .badge.status.warn{background:#fde68a;color:#92400e}
      .badge.status.bad{background:#fee2e2;color:#7f1d1d}
      .chip.channel{display:inline-block;padding:2px 8px;border-radius:999px;font-weight:700;font-size:12px}
      .chip.channel.online{background:#e0f2fe;color:#0369a1;border:1px solid #93c5fd}
      .chip.channel.cash{background:#d1fae5;color:#065f46;border:1px solid #34d399}
      .chip.pm{display:inline-block;padding:2px 8px;border-radius:999px;font-weight:700;font-size:12px;background:#e0f2fe;color:#0369a1;border:1px solid #93c5fd}
    </style>
    <?php
    $content = ob_get_clean();
    include __DIR__ . '/layout.php';
    ?>
