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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = trim($_POST['token'] ?? '');
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($token) || empty($new_password) || empty($confirm_password)) {
        echo json_encode(['success' => false, 'message' => 'Semua field harus diisi']);
        exit;
    }
    
    if ($new_password !== $confirm_password) {
        echo json_encode(['success' => false, 'message' => 'Password tidak cocok']);
        exit;
    }
    
    if (strlen($new_password) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password minimal 6 karakter']);
        exit;
    }
    
    // Verify token exists and not expired
    $stmt = $conn->prepare("SELECT id, username FROM users WHERE password_reset_token = ? AND token_expiry > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Token tidak valid atau sudah kadaluarsa']);
        exit;
    }
    
    $user = $result->fetch_assoc();
    
    // Hash password with bcrypt
    $hashed_password = password_hash($new_password, PASSWORD_BCRYPT);
    
    // Update password and clear reset token
    $updateStmt = $conn->prepare("UPDATE users SET password = ?, password_reset_token = NULL, token_expiry = NULL WHERE id = ?");
    $updateStmt->bind_param("si", $hashed_password, $user['id']);
    
    if ($updateStmt->execute()) {
        echo json_encode(['success' => true, 'message' => 'Password berhasil direset. Silakan login dengan password baru Anda']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal mereset password']);
    }
    
    $stmt->close();
    $updateStmt->close();
} else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Verify token validity
    $token = trim($_GET['token'] ?? '');
    
    if (empty($token)) {
        echo json_encode(['success' => false, 'message' => 'Token tidak ditemukan']);
        exit;
    }
    
    $stmt = $conn->prepare("SELECT id FROM users WHERE password_reset_token = ? AND token_expiry > NOW()");
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Token tidak valid atau sudah kadaluarsa']);
    } else {
        echo json_encode(['success' => true, 'message' => 'Token valid']);
    }
    
    $stmt->close();
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}

$conn->close();
?>
