<?php
require_once 'auth.php';
require_once __DIR__ . '/app/app_header.php';

$auth = getAuth();
$auth->requireAuth();
$user = $auth->getCurrentUser();
 
$alert = null;
$passwordAlert = null;

// Recupera perfil completo
$profile = $auth->getUserProfile($user['id']);
if (!$profile) {
    die('No se pudo cargar el perfil del usuario actual.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? ''; 

    if ($action === 'update_profile') {
        $fullName = $_POST['full_name'] ?? '';
        $username = $_POST['username'] ?? '';
        $email = $_POST['email'] ?? '';
        $docType = $_POST['doc_type'] ?? '';
        $docNumber = $_POST['doc_number'] ?? '';
        $country = $_POST['country'] ?? 'Colombia';

        $alert = $auth->updateProfile($user['id'], $fullName, $username, $email, $docType, $docNumber, $country);
        $profile = $auth->getUserProfile($user['id']);
    } elseif ($action === 'change_password') {
        $current = $_POST['current_password'] ?? '';
        $new = $_POST['new_password'] ?? '';
        $confirm = $_POST['confirm_password'] ?? '';
        if ($new !== $confirm) {
            $passwordAlert = ['success' => false, 'message' => 'Las contraseñas no coinciden'];
        } else {
            $passwordAlert = $auth->changePassword($user['id'], $current, $new);
        }
    }
}

function e($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
?>
<!DOCTYPE html> 
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="graphics/signatureicon.ico" type="image/x-icon">
    <title>Perfil de usuario</title>
    <style> 
        <?php echo renderAppHeaderStyles(); ?>
        * { box-sizing: border-box; }
        body { margin:0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-size:15px; background: linear-gradient(135deg, #29648D 0%, #29648D 100%); min-height:100vh; padding:20px; }
        .navbar { background: linear-gradient(135deg, #29648D 0%, #29648D 100%); color:#fff; padding:18px 34px; display:flex; justify-content:space-between; align-items:center; box-shadow:0 2px 10px rgba(0,0,0,0.1); }
        .navbar h1 { margin:0; font-size:1.35rem; }
        .navbar-actions { display:flex; gap:12px; align-items:center; flex-wrap:wrap; }
        .navbar .btn { border-radius: 20px; font-weight: 500; font-size:0.9rem; padding:10px 20px; box-shadow:none; }
        .navbar .btn-primary { background:#fff; color:#29648D; }
        .navbar .btn-outline { background:transparent; color:#fff; border:2px solid #fff; }
        .user-info { background: rgba(255,255,255,0.2); padding: 7px 12px; border-radius: 20px; font-size: 0.9rem; color:#fff; display:flex; align-items:center; gap:8px; }
        .container { max-width: 1200px; margin: 0 auto 40px; padding: 24px; background:#fff; border-radius:0 0 8px 8px; box-shadow:0 20px 60px rgba(0,0,0,0.25); }
        .grid { display:grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap:18px; }
        .card { background:#fff; border-radius:12px; box-shadow:0 10px 30px rgba(0,0,0,.08); padding:20px 18px 22px; }
        .card h2 { margin:0 0 12px; color:#29648D; font-size:1.1rem; }
        label { display:block; margin-top:12px; color:#374151; font-size:.9rem; }
        input, select { width:100%; padding:11px 12px; border:1px solid #e5e7eb; border-radius:9px; margin-top:6px; font-size:.95rem; }
        .btn { display:inline-block; padding:11px 16px; border-radius:10px; border:none; cursor:pointer; font-weight:700; text-decoration:none; }
        .btn-primary { background:#29648D; color:#fff; box-shadow:0 6px 16px rgba(41,100,141,.25); }
        .btn-outline { background:transparent; color:#fff; border:2px solid #fff; }
        .btn-ghost { background:transparent; color:#29648D; border:1px solid #29648D; }
        .actions { margin-top:16px; display:flex; gap:10px; flex-wrap:wrap; }
        .alert { padding:12px 14px; border-radius:10px; margin-bottom:12px; font-size:.9rem; }
        .alert.success { background:#ecfdf5; color:#065f46; border:1px solid #a7f3d0; }
        .alert.error { background:#fdecea; color:#b42318; border:1px solid #f1a7a1; }
        .pill { display:inline-block; padding:6px 10px; border-radius:999px; font-size:.8rem; font-weight:700; margin-right:6px; }
        .pill.ok { background:#e0f2fe; color:#075985; }
        .pill.warn { background:#fff7ed; color:#9a3412; }
        .pill.bad { background:#fef2f2; color:#b91c1c; }
        .meta { color:#6b7280; font-size:.85rem; margin-top:4px; }
        @media (max-width: 480px) {
            body { padding: 12px; }
            .container { padding: 16px; }
        }
    </style>
</head>
<body>
    <?php renderAppHeader($profile, 'perfil'); ?>

    <div class="container">
        <div class="grid">
            <div class="card">
                <h2>Información personal</h2>
                <?php if ($alert): ?>
                    <div class="alert <?php echo $alert['success'] ? 'success' : 'error'; ?>">
                        <?php echo e($alert['message']); ?>
                    </div>
                <?php endif; ?>
                <form method="post" action="">
                    <input type="hidden" name="action" value="update_profile">
                    <label>Nombre completo
                        <input type="text" name="full_name" value="<?php echo e($profile['full_name']); ?>" required>
                    </label>
                    <label>Usuario
                        <input type="text" name="username" value="<?php echo e($profile['username']); ?>" required>
                    </label>
                    <label>Email
                        <input type="email" name="email" value="<?php echo e($profile['email']); ?>" required>
                    </label>
                    <label>Tipo de documento
                        <select name="doc_type" required>
                            <?php
                            $docTypes = ['CC' => 'Cédula de ciudadanía', 'CE' => 'Cédula de extranjería', 'LC' => 'Licencia de conducción', 'PA' => 'Pasaporte', 'NIT' => 'NIT', 'OTRO' => 'Otro'];
                            foreach ($docTypes as $value => $label):
                            ?>
                                <option value="<?php echo e($value); ?>" <?php echo ($profile['doc_type'] === $value) ? 'selected' : ''; ?>>
                                    <?php echo e($label); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <label>Número de documento
                        <input type="text" name="doc_number" value="<?php echo e($profile['doc_number']); ?>" required>
                    </label>
                    <label>País
                        <select name="country" required>
                            <?php
                            $countries = ['Colombia','Argentina','Chile','Peru','Mexico','Otro'];
                            foreach ($countries as $countryOpt):
                            ?>
                                <option value="<?php echo e($countryOpt); ?>" <?php echo ($profile['country'] === $countryOpt) ? 'selected' : ''; ?>>
                                    <?php echo e($countryOpt); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </label>
                    <div class="actions">
                        <button class="btn btn-primary" type="submit">Actualizar datos</button>
                    </div>
                </form>
            </div>

            <div class="card">
                <h2>Seguridad</h2>
                <?php if ($passwordAlert): ?>
                    <div class="alert <?php echo $passwordAlert['success'] ? 'success' : 'error'; ?>">
                        <?php echo e($passwordAlert['message']); ?>
                    </div>
                <?php endif; ?>
                <form method="post" action="">
                    <input type="hidden" name="action" value="change_password">
                    <label>Contraseña actual
                        <input type="password" name="current_password" required>
                    </label>
                    <label>Nueva contraseña
                        <input type="password" name="new_password" minlength="8" required>
                    </label>
                    <label>Confirmar nueva contraseña
                        <input type="password" name="confirm_password" minlength="8" required>
                    </label>
                    <div class="actions">
                        <button class="btn btn-primary" type="submit">Cambiar contraseña</button>
                    </div>
                </form>

                <div style="margin-top:16px;">
                    <h3 style="margin:0 0 8px; color:#374151;">Estado de cuenta</h3>
                    <span class="pill <?php echo ($profile['status'] === 'activo') ? 'ok' : 'warn'; ?>">
                        <?php echo e($profile['status']); ?>
                    </span>
                    <span class="pill <?php
                        $k = $profile['kyc_estado'] ?? 'no_iniciado';
                        echo ($k === 'verificado') ? 'ok' : (($k === 'rechazado') ? 'bad' : 'warn');
                    ?>">
                        KYC: <?php echo e($profile['kyc_estado'] ?? 'no_iniciado'); ?>
                    </span>
                    <?php if (!empty($profile['kyc_verificado_el'])): ?>
                        <div class="meta">Verificado el: <?php echo e($profile['kyc_verificado_el']); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($profile['kyc_motivo_resultado'])): ?>
                        <div class="meta">Detalle: <?php echo e($profile['kyc_motivo_resultado']); ?></div>
                    <?php endif; ?>
                    <div class="actions" style="margin-top:12px;">
                        <a class="btn btn-ghost" href="kyc">Gestionar KYC</a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
