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

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

$error = '';
$success = false;
$email = '';

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitize($_POST['email']);
    
    // Validate input
    if (empty($email)) {
        $error = 'Silakan masukkan alamat email Anda';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Format email tidak valid';
    } else {
        try {
            $conn = connectDB();
            $stmt = $conn->prepare("SELECT user_id, username, phone FROM users WHERE email = :email");
            $stmt->bindParam(':email', $email);
            $stmt->execute();
            
            if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
                // Generate unique token
                $token = bin2hex(random_bytes(32));
                $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
                
                // Save token to database
                $stmt = $conn->prepare("UPDATE users SET reset_token = :token, reset_expiry = :expiry WHERE user_id = :user_id");
                $stmt->bindParam(':token', $token);
                $stmt->bindParam(':expiry', $expiry);
                $stmt->bindParam(':user_id', $user['user_id']);
                $stmt->execute();
                
                // Prepare reset link for WhatsApp
                $resetLink = urlencode(SITE_URL . 'user/reset_password.php?token=' . $token);
                
                $rawPhoneNumber = isset($user['phone']) ? (string)$user['phone'] : '';
                $whatsappNumber = ''; // Initialize as empty string
                
                if (!empty($rawPhoneNumber)) {
                    // Remove all non-numeric characters
                    $cleanedNumber = preg_replace('/[^0-9]/i', '', $rawPhoneNumber);
                    
                    if (!empty($cleanedNumber)) {
                        // If starts with '0', replace it with '62'
                        if (substr($cleanedNumber, 0, 1) === '0') {
                            $whatsappNumber = '62' . substr($cleanedNumber, 1);
                        // If doesn't start with '62' and is a long number, prepend '62'
                        } elseif (substr($cleanedNumber, 0, 2) !== '62' && strlen($cleanedNumber) >= 8) {
                            $whatsappNumber = '62' . $cleanedNumber;
                        } else {
                            // Otherwise, use the cleaned number as is (assuming it's already in correct international format or needs no change)
                            $whatsappNumber = $cleanedNumber;
                        }
                    }
                }
                
                // Check if whatsappNumber is still empty after formatting
                if (empty($whatsappNumber)) {
                    $whatsappLink = '#'; // Set to # if no valid number is found
                    $error = 'Nomor telepon tidak ditemukan atau tidak valid untuk akun ini.';
                } else {
                    $message = urlencode("Halo, Anda telah meminta untuk mereset kata sandi Anda. Silakan klik tautan berikut untuk mereset kata sandi Anda: ");
                    $whatsappLink = "https://wa.me/" . $whatsappNumber . "?text=" . $message . $resetLink;
                }
                echo "<div class='success'>Debug WhatsApp Link: <a href='" . htmlspecialchars($whatsappLink) . "' target='_blank'>" . htmlspecialchars($whatsappLink) . "</a></div>";
                
                $success = true;
                $email = ''; // Clear email after success
            } else {
                $error = 'Gagal membuat tautan reset. Silakan coba lagi.';
            }
        } 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>Lupa 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">
    <style>
        body {
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        
        .forgot-password-container {
            background: white;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
        }
        
        .forgot-password-container h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        
        .forgot-password-logo {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .forgot-password-logo h1 {
            color: var(--primary-color);
            font-size: 24px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .btn {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
        }
        
        .btn:hover {
            background-color: #3a8f3a;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .forgot-password-footer {
            margin-top: 20px;
            text-align: center;
            font-size: 14px;
        }
        
        .forgot-password-footer a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .forgot-password-footer a:hover {
            text-decoration: underline;
        }
        
        .back-to-login {
            display: block;
            text-align: center;
            margin-top: 15px;
            color: #666;
        }
        
        .reset-instructions {
            background-color: #fff3cd;
            color: #856404;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
            font-size: 14px;
            line-height: 1.5;
        }
        
        .reset-link {
            background-color: #e9ecef;
            padding: 10px;
            border-radius: 4px;
            word-break: break-all;
            margin: 10px 0;
            font-family: monospace;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="forgot-password-container">
        <div class="forgot-password-logo">
            <h1><?php echo SITE_NAME; ?></h1>
            <p>Lupa Password</p>
        </div>
        
        
        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="success">
                Permintaan reset kata sandi Anda telah diproses. Silakan ikuti petunjuk di bawah ini.
            </div>
            <div class="reset-instructions">
                <p>Petunjuk untuk mendapatkan tautan reset kata sandi via WhatsApp:</p>
                <ol>
                    <li>Pastikan nomor telepon yang terdaftar pada akun Anda terhubung dengan WhatsApp aktif.</li>
                    <li>Klik tombol hijau <span style="font-weight: bold;">"Kirim Pesan WhatsApp"</span> di bawah ini.</li>
                    <li>Anda akan diarahkan ke aplikasi WhatsApp (atau WhatsApp Web) dengan pesan yang sudah terisi.</li>
                    <li><strong style="color: #e74c3c;">PENTING:</strong> Di aplikasi WhatsApp, silakan <strong style="color: #e74c3c;">TEKAN TOMBOL KIRIM</strong> untuk mengirim pesan yang berisi tautan reset Anda.</li>
                    <li>Setelah pesan terkirim, Anda akan menerima balasan dengan tautan reset kata sandi.</li>
                    <li>Klik tautan tersebut untuk membuat kata sandi baru Anda.</li>
                </ol>
                <p>Tautan akan kedaluwarsa dalam 1 jam.</p>
                <a href="<?php echo isset($whatsappLink) ? $whatsappLink : '#'; ?>" class="btn" target="_blank" style="background-color: #25D366; margin-top: 15px;"><i class="fab fa-whatsapp"></i> Kirim Pesan WhatsApp</a>
            </div>
        <?php else: ?>
            <form action="forgot_password.php" method="post">
                <div class="form-group">
                    <label for="email">Alamat Email:</label>
                    <input type="email" id="email" name="email" value="<?php echo $email; ?>" required>
                    <small>Masukkan alamat email yang terdaftar pada akun Anda.</small>
                </div>
                
                <button type="submit" class="btn">Kirim Permintaan Reset</button>
            </form>
        <?php endif; ?>
        
        <div class="forgot-password-footer">
            <a href="login.php" class="back-to-login">
                <i class="fas fa-arrow-left"></i> Kembali ke halaman login
            </a>
        </div>
    </div>
</body>
</html> 