<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

check_role('administrador');

$user_id = sanitize_get('id', 'int');
if (!$user_id) {
    header('Location: users.php');
    exit;
}

// Get user information
$stmt = $pdo->prepare("SELECT u.id, u.username, u.email, u.first_name, u.last_name, r.name as role FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ? AND u.deleted_at IS NULL");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    header('Location: users.php');
    exit;
}

$page_title = 'Cambiar Contraseña - ' . htmlspecialchars($user['username']);

$content = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $new_password = sanitize_post('new_password', 'string', ['max_length' => 255]);
    $confirm_password = sanitize_post('confirm_password', 'string', ['max_length' => 255]);

    $errors = [];

    if (empty($new_password)) {
        $errors[] = 'La nueva contraseña es requerida.';
    } elseif (strlen($new_password) < 8) {
        $errors[] = 'La contraseña debe tener al menos 8 caracteres.';
    }

    if ($new_password !== $confirm_password) {
        $errors[] = 'Las contraseñas no coinciden.';
    }

    if (empty($errors)) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        $update_stmt = $pdo->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?");
        $update_stmt->execute([$hashed_password, $user_id]);

        log_database_change('UPDATE', 'users', $user_id, ['password' => '[HIDDEN]'], ['password' => '[CHANGED]']);

        set_flash_message('success', 'Contraseña cambiada exitosamente.');
        header('Location: users.php');
        exit;
    } else {
        $content .= '<div class="alert alert-danger"><ul>';
        foreach ($errors as $error) {
            $content .= '<li>' . htmlspecialchars($error) . '</li>';
        }
        $content .= '</ul></div>';
    }
}

$content .= '
<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Cambiar Contraseña</h3>
                <div class="card-tools">
                    <a href="users.php" class="btn btn-secondary btn-sm">
                        <i class="fas fa-arrow-left"></i> Volver
                    </a>
                </div>
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <strong>Usuario:</strong> ' . htmlspecialchars($user['username']) . '<br>
                    <strong>Email:</strong> ' . htmlspecialchars($user['email']) . '<br>
                    <strong>Nombre:</strong> ' . htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) . '<br>
                    <strong>Rol:</strong> ' . ucfirst($user['role']) . '
                </div>

                <form method="post">
                    <div class="mb-3">
                        <label for="new_password" class="form-label">Nueva Contraseña</label>
                        <input type="password" class="form-control" id="new_password" name="new_password" required minlength="8">
                        <div class="form-text">La contraseña debe tener al menos 8 caracteres.</div>
                    </div>

                    <div class="mb-3">
                        <label for="confirm_password" class="form-label">Confirmar Nueva Contraseña</label>
                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" required minlength="8">
                    </div>

                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-key"></i> Cambiar Contraseña
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>';

include BASE_PATH . '/includes/layout.php';
?>