<?php
require_once '../includes/config.php';

// Check if user is already logged in
if (isUserLoggedIn()) {
    redirect(SITE_URL);
}

$error = '';
$success = false;
$token = '';

// Check if token exists in URL
if (isset($_GET['token'])) {
    $token = $_GET['token'];
} else {
    $error = 'Token reset password tidak valid atau telah kedaluwarsa.';
}

// Verify token exists and not expired
if (!empty($token)) {
    try {
        $conn = connectDB();
        $stmt = $conn->prepare("SELECT * FROM users WHERE reset_token = :token AND reset_expiry > NOW()");
        $stmt->bindParam(':token', $token);
        $stmt->execute();
        
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            $error = 'Token reset password tidak valid atau telah kedaluwarsa.';
            $token = '';
        }
    } catch (PDOException $e) {
        $error = 'Terjadi kesalahan: ' . $e->getMessage();
        $token = '';
    }
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($token)) {
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validate input
    if (empty($password) || empty($confirm_password)) {
        $error = 'Silakan lengkapi semua bidang';
    } elseif ($password !== $confirm_password) {
        $error = 'Kata sandi dan konfirmasi kata sandi tidak cocok';
    } elseif (strlen($password) < 6) {
        $error = 'Kata sandi harus minimal 6 karakter';
    } else {
        try {
            $conn = connectDB();
            // This redundant query can be removed, as $user is already fetched and validated if !empty($token)
            // $stmt = $conn->prepare("SELECT * FROM users WHERE reset_token = :token AND reset_expiry > NOW()");
            // $stmt->bindParam(':token', $token);
            // $stmt->execute();
            
            // Use the $user object already fetched if the token was valid on page load
            if ($user) {
                // Hash the new password
                $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
                
                // Update password and remove token
                $stmt = $conn->prepare("UPDATE users SET password = :password, reset_token = NULL, reset_expiry = NULL WHERE user_id = :user_id");
                $stmt->bindParam(':password', $hashedPassword);
                $stmt->bindParam(':user_id', $user['user_id']);
                
                if ($stmt->execute()) {
                    $success = true;
                    $token = ''; // Clear token after successful reset
                } else {
                    $error = 'Gagal menyimpan kata sandi baru. Silakan coba lagi.';
                }
            } else {
                // This case should ideally not be reached if !empty($token) and $user was initially valid
                $error = 'Token reset password tidak valid atau telah kedaluwarsa.';
                $token = '';
            }
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reset Password - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    </head>
<body class="reset-password-page">
    <div class="reset-password-container">
        <div class="reset-password-logo">
            <h1><?php echo SITE_NAME; ?></h1>
            <p>Reset Kata Sandi</p>
        </div>
        
        <h2>Buat Kata Sandi Baru</h2>
        
        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="success">
                Kata sandi Anda berhasil diubah! Silakan <a href="login.php">login</a> dengan kata sandi baru Anda.
            </div>
        <?php elseif (!empty($token)): ?>
            <form action="reset_password.php?token=<?php echo $token; ?>" method="post">
                <div class="form-group">
                    <label for="password">Kata Sandi Baru:</label>
                    <div class="password-input-wrapper">
                        <input type="password" id="password" name="password" required minlength="6" oninput="checkPasswordStrength(this.value)">
                        <span class="password-toggle" onclick="togglePassword('password')">
                            <i class="far fa-eye" id="password-toggle-icon"></i>
                        </span>
                    </div>
                    <small>Kata sandi minimal 6 karakter</small>
                    <div class="password-strength">Kekuatan Kata Sandi: <span id="password-strength-text">Belum diisi</span></div>
                    <div class="password-strength-meter">
                        <div id="password-strength-meter-bar"></div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="confirm_password">Konfirmasi Kata Sandi Baru:</label>
                    <div class="password-input-wrapper">
                        <input type="password" id="confirm_password" name="confirm_password" required minlength="6">
                        <span class="password-toggle" onclick="togglePassword('confirm_password')">
                            <i class="far fa-eye" id="confirm_password-toggle-icon"></i>
                        </span>
                    </div>
                </div>
                
                <button type="submit" class="btn">Simpan Kata Sandi Baru</button>
            </form>
        <?php endif; ?>
        
        <div class="reset-password-footer">
            <a href="login.php" class="back-to-login">
                <i class="fas fa-arrow-left"></i> Kembali ke halaman login
            </a>
        </div>
    </div>
    
    <script>
        function togglePassword(inputId) {
            const passwordInput = document.getElementById(inputId);
            const toggleIcon = document.getElementById(inputId + '-toggle-icon');
            
            if (passwordInput) {
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    toggleIcon.classList.remove('fa-eye');
                    toggleIcon.classList.add('fa-eye-slash');
                } else {
                    passwordInput.type = 'password';
                    toggleIcon.classList.remove('fa-eye-slash');
                    toggleIcon.classList.add('fa-eye');
                }
            }
        }
        
        function checkPasswordStrength(password) {
            const strengthText = document.getElementById('password-strength-text');
            const strengthMeter = document.getElementById('password-strength-meter-bar');
            
            if (!password) {
                strengthText.textContent = 'Belum diisi';
                strengthMeter.className = '';
                strengthMeter.style.width = '0';
                return;
            }
            
            // Check strength
            let strength = 0;
            
            // Length check
            if (password.length >= 6) strength += 1;
            if (password.length >= 10) strength += 1;
            
            // Character type check
            if (/[A-Z]/.test(password)) strength += 1;
            if (/[0-9]/.test(password)) strength += 1;
            if (/[^A-Za-z0-9]/.test(password)) strength += 1;
            
            // Update UI based on strength
            if (strength <= 2) {
                strengthText.textContent = 'Lemah';
                strengthMeter.className = 'strength-weak';
            } else if (strength <= 3) {
                strengthText.textContent = 'Sedang';
                strengthMeter.className = 'strength-medium';
            } else if (strength <= 4) {
                strengthText.textContent = 'Kuat';
                strengthMeter.className = 'strength-strong';
            } else {
                strengthText.textContent = 'Sangat Kuat';
                strengthMeter.className = 'strength-very-strong';
            }
        }
    </script>
</body>
</html> 