<?php
session_start();
include('config/koneksi.php');


if (!isset($_SESSION['reset_member_id'])) {
    header("Location: ../lupaPassword.php?error=" . urlencode("Silakan masukkan email terlebih dahulu."));
    exit();
}

$error = "";
$success = "";

function validatePassword($password, $confirm) {
    if (strlen($password) < 8) {
        return "Password harus minimal 8 karakter.";
    }
    if (!preg_match('/[A-Za-z]/', $password) || !preg_match('/\d/', $password)) {
        return "Password harus mengandung huruf dan angka.";
    }
    if ($password !== $confirm) {
        return "Konfirmasi password tidak cocok.";
    }
    return null;
}

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

    $error = validatePassword($password, $confirm);

    if (!$error) {
        $hashedPassword = md5($password);
        $stmt = $conn->prepare("UPDATE members SET password = ? WHERE member_id = ?");
        $stmt->bind_param("si", $hashedPassword, $_SESSION['reset_member_id']);

        if ($stmt->execute()) {
            $success = "Password berhasil diubah. Silakan <a href='login.php'>login</a>.";
            unset($_SESSION['reset_member_id']);
        } else {
            $error = "Gagal mengubah password.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Reset Password LEON GYM</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/login.css">
</head>
<body>
<div class="login-box">
    <h2>Reset Password</h2>

    <?php if ($error): ?>
        <div class="error"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <?php if ($success): ?>
        <div class="success"><?= $success ?></div>
    <?php else: ?>
        <form method="post" action="">
            <input type="password" name="password" placeholder="Password Baru (min 8 karakter)" required minlength="8"><br><br>
            <input type="password" name="confirm" placeholder="Konfirmasi Password" required minlength="8"><br><br>
            <button type="submit">Ganti Password</button>
        </form>
    <?php endif; ?>
</div>
</body>
</html>
