<?php
header('Content-Type: application/json');
include 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    
    if (empty($email)) {
        echo json_encode(['success' => false, 'message' => 'Email tidak boleh kosong']);
        exit;
    }
    
    // Check if email exists
    $stmt = $conn->prepare("SELECT id, username, full_name FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        // Don't reveal if email exists or not (security best practice)
        echo json_encode(['success' => true, 'message' => 'Jika email terdaftar, link reset password akan dikirim']);
        exit;
    }
    
    $user = $result->fetch_assoc();
    
    // Generate reset token (valid for 1 hour)
    $reset_token = bin2hex(random_bytes(32));
    $token_expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
    
    // Store token in database
    $updateStmt = $conn->prepare("UPDATE users SET password_reset_token = ?, token_expiry = ? WHERE id = ?");
    $updateStmt->bind_param("ssi", $reset_token, $token_expiry, $user['id']);
    
    if ($updateStmt->execute()) {
        // Send email with reset link
        $reset_link = "http://localhost/logbook-ppds/reset-password.html?token=" . $reset_token;
        $email_subject = "Reset Password - E-LOGBOOK PPDS-2";
        $email_body = "Halo " . $user['full_name'] . ",\n\n";
        $email_body .= "Anda telah meminta untuk reset password. Silakan klik link di bawah untuk reset password Anda:\n\n";
        $email_body .= $reset_link . "\n\n";
        $email_body .= "Link ini hanya berlaku selama 1 jam.\n\n";
        $email_body .= "Jika Anda tidak meminta reset password, abaikan email ini.\n\n";
        $email_body .= "Regards,\nE-LOGBOOK PPDS-2";
        
        $email_headers = "From: noreply@logbook-ppds.local\r\n";
        $email_headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
        
        // Try to send email
        if (mail($email, $email_subject, $email_body, $email_headers)) {
            echo json_encode(['success' => true, 'message' => 'Link reset password telah dikirim ke email Anda']);
        } else {
            // Email failed, but for demo purposes, show the reset link
            echo json_encode([
                'success' => true,
                'message' => 'Email tidak dapat dikirim, namun Anda dapat menggunakan link berikut untuk reset password (demo): ' . $reset_link,
                'demo_link' => $reset_link
            ]);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal memproses permintaan reset password']);
    }
    
    $stmt->close();
    $updateStmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
