<?php
session_start();
include 'conexion.php';

// Verificar si el usuario ha iniciado sesión y tiene el rol correcto
if (!isset($_SESSION['rol']) || $_SESSION['rol'] !== 'propietario') {
    header("Location: login.php");
    exit;
}

$id_usuario = $_SESSION['id_usuario'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $contrasena_actual = $_POST['contrasena_actual'];
    $nueva_contrasena = $_POST['nueva_contrasena'];
    $confirmar_contrasena = $_POST['confirmar_contrasena'];

    if ($nueva_contrasena !== $confirmar_contrasena) {
        $error = "Las contraseñas no coinciden.";
    } else {
        // Verificar la contraseña actual
        $stmt = $conn->prepare("SELECT password FROM usuarios WHERE id_usuario = ?");
        if (!$stmt) {
            die("Error en la consulta: " . $conn->error);
        }
        $stmt->bind_param("i", $id_usuario);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows === 1) {
            $usuario = $result->fetch_assoc();

            if (password_verify($contrasena_actual, $usuario['password'])) {
                // Actualizar la contraseña
                $hash = password_hash($nueva_contrasena, PASSWORD_DEFAULT);
                $stmt_update = $conn->prepare("UPDATE usuarios SET password = ? WHERE id_usuario = ?");
                if (!$stmt_update) {
                    die("Error en la consulta de actualización: " . $conn->error);
                }
                $stmt_update->bind_param("si", $hash, $id_usuario);

                if ($stmt_update->execute()) {
                    $mensaje = "Contraseña actualizada con éxito.";
                } else {
                    $error = "Error al actualizar la contraseña.";
                }
            } else {
                $error = "La contraseña actual no es correcta.";
            }
        } else {
            $error = "Usuario no encontrado.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cambiar Contraseña</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <!-- Navbar -->
    <nav class="main-header navbar navbar-expand navbar-white navbar-light">
        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" data-widget="pushmenu" href="#" role="button"><i class="fas fa-bars"></i></a>
            </li>
        </ul>
    </nav>

    <!-- Sidebar -->
    <aside class="main-sidebar sidebar-dark-primary elevation-4">
        <a href="#" class="brand-link">
            <span class="brand-text font-weight-light">Sistema Arriendos</span>
        </a>
        <div class="sidebar">
            <div class="user-panel mt-3 pb-3 mb-3 d-flex">
                <div class="info">
                    <a href="#" class="d-block">Propietario</a>
                </div>
            </div>
            <nav class="mt-2">
                <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu">
                    <li class="nav-item">
                        <a href="propietario_dashboard.php" class="nav-link">
                            <i class="nav-icon fas fa-home"></i>
                            <p>Dashboard</p>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="cambiar_contrasena.php" class="nav-link active">
                            <i class="nav-icon fas fa-key"></i>
                            <p>Cambiar Contraseña</p>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </aside>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1>Cambiar Contraseña</h1>
                    </div>
                </div>
            </div>
        </section>

        <section class="content">
            <div class="container-fluid">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                <?php if (isset($mensaje)): ?>
                    <div class="alert alert-success"><?php echo $mensaje; ?></div>
                <?php endif; ?>
                <form method="POST" action="">
                    <div class="mb-3 position-relative">
                        <label for="contrasena_actual" class="form-label">Contraseña Actual</label>
                        <input type="password" class="form-control" id="contrasena_actual" name="contrasena_actual" required>
                        <i class="fas fa-eye-slash position-absolute top-50 end-0 translate-middle-y pe-3 toggle-password" data-target="contrasena_actual" style="cursor: pointer;"></i>
                    </div>
                    <div class="mb-3 position-relative">
                        <label for="nueva_contrasena" class="form-label">Nueva Contraseña</label>
                        <input type="password" class="form-control" id="nueva_contrasena" name="nueva_contrasena" required>
                        <i class="fas fa-eye-slash position-absolute top-50 end-0 translate-middle-y pe-3 toggle-password" data-target="nueva_contrasena" style="cursor: pointer;"></i>
                    </div>
                    <div class="mb-3 position-relative">
                        <label for="confirmar_contrasena" class="form-label">Confirmar Nueva Contraseña</label>
                        <input type="password" class="form-control" id="confirmar_contrasena" name="confirmar_contrasena" required>
                        <i class="fas fa-eye-slash position-absolute top-50 end-0 translate-middle-y pe-3 toggle-password" data-target="confirmar_contrasena" style="cursor: pointer;"></i>
                    </div>
                    <button type="submit" class="btn btn-primary w-100">Actualizar Contraseña</button>
                </form>
            </div>
        </section>
    </div>
</div>

<script>
    document.querySelectorAll('.toggle-password').forEach(icon => {
        icon.addEventListener('click', () => {
            const targetId = icon.getAttribute('data-target');
            const input = document.getElementById(targetId);
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            }
        });
    });
</script>
</body>
</html>
