<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/auth.php';

checkSession();

$pageTitle = 'Mi Perfil';

$currentUserId = getCurrentUserId();
if ($currentUserId === 0) {
    header('Location: login.php');
    exit;
}

$user = getUserById($currentUserId);
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (empty($currentPassword) || empty($newPassword) || empty($confirmPassword)) {
            $error = 'Todos los campos son requeridos';
        } elseif ($newPassword !== $confirmPassword) {
            $error = 'Las contraseñas no coinciden';
        } elseif (strlen($newPassword) < 6) {
            $error = 'La contraseña debe tener al menos 6 caracteres';
        } else {
            $pdo = getDbConnection();
            $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
            $stmt->execute([$user['id']]);
            $result = $stmt->fetch();
            
            if (!$result) {
                $error = 'Error al obtener datos del usuario';
            } else {
                $currentHash = $result['password'];
                
                if (!password_verify($currentPassword, $currentHash)) {
                    $error = 'La contraseña actual es incorrecta';
                } else {
                    updateUserPassword($user['id'], $newPassword);
                    logActivity($user['id'], 'change_password', 'Usuario cambió su contraseña');
                    $success = 'Contraseña actualizada correctamente';
                }
            }
        }
    }
}

require_once __DIR__ . '/templates/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-person"></i> Mi Perfil</h2>
</div>

<div class="row">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center">
                <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                    <i class="bi bi-person text-primary" style="font-size: 40px;"></i>
                </div>
                <h4><?= htmlspecialchars($user['username']) ?></h4>
                <span class="badge bg-<?= $user['role'] === 'admin' ? 'danger' : 'primary' ?>">
                    <?= strtoupper($user['role']) ?>
                </span>
                <hr>
                <p class="text-muted mb-1">ID: <?= $user['id'] ?></p>
                <p class="text-muted mb-0">Miembro desde: <?= date('d/m/Y', strtotime($user['created_at'])) ?></p>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <?php if ($error): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>
        
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0">
                <h5 class="mb-0"><i class="bi bi-key"></i> Cambiar Contraseña</h5>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="change_password">
                    
                    <div class="mb-3">
                        <label class="form-label">Contraseña Actual</label>
                        <input type="password" name="current_password" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Nueva Contraseña</label>
                        <input type="password" name="new_password" class="form-control" required minlength="6">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Confirmar Nueva Contraseña</label>
                        <input type="password" name="confirm_password" class="form-control" required minlength="6">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-check-circle"></i> Actualizar Contraseña
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
